javascript中的浅拷贝和深拷贝有什么区别?
This article will explore the common challenges and solutions for cloning objects in JavaScript. When attempting to create a copy of an object, if the result does not meet expectations, this article will thoroughly analyze various cloning techniques and their correct application methods. These insights will help ensure consistent and predictable output when using cloning operations.
In JavaScript, object cloning can be categorized into shallow and deep cloning. This article will delve into the meanings and implementation methods of both mechanisms.
Shallow Copy
In JavaScript, a shallow copy creates a new object that references the same memory location as the original object. This means that modifying properties of the copied object will also affect the original object.
Several methods exist to implement shallow copying:
Object.assign()
The Object.assign() method copies all enumerable properties from source objects to a target object. Its syntax is: Object.assign(target, ...sources), where target is the destination object and sources are the source objects. The following example demonstrates its usage:
let originalObj = { name: "John", age: 30 };
let copiedObj = Object.assign({}, originalObj);
copiedObj.age = 40;
console.log(originalObj.age); // Output: 40
As shown in the example, modifying properties of the copied object will cause the original object to be synchronized.
Spread Operator (...)
The spread operator can also be used to create a shallow copy of an object. This operator distributes the properties of the source object into a new object. The following example demonstrates its usage:
let originalObj = { name: "John", age: 30 };
let copiedObj = { ...originalObj };
copiedObj.age = 40;
console.log(originalObj.age); // Output: 40
Similarly, modifying properties of the copied object will affect the original object.
Deep Copy
A deep copy creates a completely independent new object, containing all properties and nested properties of the original object. This means that modifications to the copied object will not affect the original object.
Common methods for implementing deep copying in JavaScript include:
Recursive Cloning
Here is an example of deep cloning implemented using recursion:
function deepClone(obj) {
if (obj === null || typeof obj !== 'object') {
return obj;
}
const clone = {};
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
clone[key] = deepClone(obj[key]);
}
}
return clone;
}
Note: This example is suitable for simple object structures and does not handle complex scenarios like cyclic references.
