Shallow copy
Let a = {name: “I am a”}
/* a’s memory address points to the contents of stack memory, */
// Shallow copy only copies the memory address of A in stack memory
// If you change the contents of B’s memory address, A will also be changed because they both point to the same heap.
let b = a
console.log(b); // {name:” I am a”}
B. name = “I am b” // the name attribute of b is changed.
console.log(b); / / {name: “I am a b}”
console.log(a); //{name:” I am b”} // Because the heap memory contents in the memory address have been changed
Deep copy
Method 1: Copy the object, copy only one layer, the following ultimate solution can really do the deep copy (object and array) idea encapsulates a method to pass in the deep copy object, and then for in traversal, method returns a new object (copied object).
Function copyObj(obj) {let result = {} for (let key in obj) {result[key] = obj[key]} return result} Let a = {name: “I am a”, age: “Awdaw”} let b = copyObj(a);} let b = copyObj(a); //{name:” I am b”, age:”awdaw”} console.log(a); //{name: “I am a”, age: “Awdaw “} Function copyObj(obj) {let result = {} for (let key in obj) {result[key] = obj[key]} return result } let a = [1, 2, 3, 4, 5, 6, 7, 8] let b = copyObj(a); // Let b = copyObj(a); //[” modify “, 2, 3, 4, 5, 6, 7, 8] console.log(a); //[1, 2, 3, 4, 5, 6, 7, 8]
Final solution: Deep-copy objects + arrays are deep-copied regardless of whether the values are complex types
Function copyObj(obj) {function copyObj(obj) {function copyObj(obj) { if (Object.prototype.toString.call(obj) == “[object Array]”) { result = [] } else if (Object. The prototype. ToString. Call (obj) = = “[Object Object]”) {result = {}} else {return “please input the correct complex data type”} for (let the key In obj) {// Use recursion!!!!! If (typeof obj[key] == “object”) {result[key] = copyObj(obj[key]) if (typeof obj[key] == “object”) {name:122}} {name:122} {name:122}} Break} result[key] = obj[key]} return result}
let obj = {
name: 111, two: {
name: 122, age: {
w: 1111
}
}
}
// Make a deep copy of the object
let newObj = copyObj(obj)
Newobj.two-age. w = “I am also modified”
Newobj.two-name = “I changed it”
console.log(newObj);
console.log(obj);
// The modified result does not affect the copied object
// Make a deep copy of the array
Let arr = [1, 2, 3, 4, 5, 6, [” second, “{name:” the complex type “in the second}]]
let newArr = copyObj(arr)
// Changing the contents of newArr will not affect arR
NewArr [6][0] = “I also changed” // does not affect arR
NewArr [6][1]. Name = “changed” // does not affect arR
console.log(newArr);
console.log(arr);
// The modified result does not affect the copied array