How do I check the deep copy? Does the object have different references before and after the copy, so it's true by comparison?

Asked 1 years ago, Updated 1 years ago, 25 views

How do I check the deep copy?
·Because the reference destinations of objects are different before and after copying, is there any chance that they will be true in comparison
·If the values of each property match in the loop, is it correct to judge that deep copying is possible?

Assumed Case

JSON.parse(JSON.stringify(obj));

You want to determine if the object created in is a deep copy.

add

"·How can I confirm by conditional branching that ""one object"" is a deep copy of ""another object"" (when using npm clone, etc.)?"

var clone=require('clone');

vara,b;

a = {foo:{bar:'baz'}}; // initial value of a 

b = clone(a); // clone a->b 
// a.foo.bar = 'foo'; // change a 

console.log(a); // show a 
console.log(b);

console.log(a==b); // false
console.log(a===b); // false

javascript

2022-09-30 18:41

1 Answers

Deep copy is a language in which references to objects can be retained, and when copying composite objects, how to copy references to child objects contained therein

  • Reproduce references as they are: Shallow Copy
  • Duplicate entity: Deep copy

That's the only definition.

Replicating the substance is, in short, "creating by copying the same thing."

vara={foo:[1,2], bar:{x:1};
a.self=a;

varb = {foo:[1,2], bar: {x:1};
b.self=b;

I created b by imitating the existing object a exactly as it is, but I didn't see any part of a from b.This is a deep copy of the program.

Specific and how to replicate depends on what is difficult to replicate (such as a closure for JS), what you don't want to replicate (such as a DOM object), and what you want to replicate and how you want to replicate.

Once the specifications are clear, you just need to check in order to see if they are all working properly.For example, the clone library at npm also has a test code.

https://github.com/pvorb/clone/blob/master/test.js

If the values of each property match in the loop, is it correct to conclude that deep copying is possible?

If you want to compare the values of properties recursively, you have the right idea.However, if you leave the recursive structure intact, it will be an infinite loop, and if you want to reproduce the properties defined in Object.defineProperty(), you will also need to choose how to enumerate and compare the properties.


2022-09-30 18:41

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.