SoFunction
Updated on 2025-03-06

Several common ways to copy JavaScript objects and arrays

1. Quotation assignment: simple and efficient data sharing

concept:Reference assignment is the easiest operation in JavaScript. It does not really create a copy of the object, but instead lets the new variable share the same memory address as the original variable. When you modify a new variable, the data of the original variable will also be modified.

Code example:

let person = { name: "Alice", age: 25 };
let newPerson = person;
 = 30;
();  // Output 30

Applicable scenarios:

  • Unnecessary replication can be avoided when memory and performance requirements are required.
  • Scenarios that need to share data or remain synchronized, such as state management or configuration sharing.

advantage:

  • Efficient and memory saving.

shortcoming:

  • Modifying new variables will affect the original object and easily cause side effects.

2. Shallow copy: copy top-level properties

A shallow copy creates a new object, copying the top-level properties of the original object, but if the properties are reference types (such as objects, arrays), they still point to the original memory address.

1. Extended operator...

Code example:

let person = { name: "Alice", age: 25, details: { city: "New York" } };
let newPerson = { ...person };
 = "Los Angeles";
();  // Output "Los Angeles"

Applicable scenarios:

  • The object structure is simple, or only requires shallow modification.

2. ()

()It is also a shallow copy method, suitable for merging multiple objects into the target object.

Code example:

let target = { a: 1 };
let source = { b: 2 };
let newObject = (target, source);

Applicable scenarios:

  • It is especially suitable for object merging operations when you need to merge multiple objects.

3.  () and  concat()

For arrays, you can useslice()orconcat()To create a shallow copy.

Code example:

let arr = [1, 2, 3];
let shallowCopy = ();

Applicable scenarios:

  • Suitable for processing simple arrays without involving deep data.

3. Deep copy: complete object copy

Deep copy refers to recursive copying of an object or array to ensure that nested objects at all levels have independent copies. Modifying the new object will not affect the original object.

1. Recursively implement deep copy

Code example:

function deepClone(obj) {
    if (obj === null || typeof obj !== 'object') return obj;
    let copy = (obj) ? [] : {};
    for (let key in obj) {
        if ((key)) {
            copy[key] = deepClone(obj[key]);
        }
    }
    return copy;
}

Applicable scenarios:

  • When the object structure is complex and a completely independent copy is required.

2. (())

This method can quickly implement deep copy, but it has some limitations, such as the inability to copy functions,DateRegExpSpecial types.

Code example:

let original = { a: 1, b: { c: 2 } };
let copy = ((original));

Applicable scenarios:

  • Suitable for simple object structures and do not include special types.

3. structuredClone()

structuredClone()It is a more advanced deep copy method that can be processedDateMapSetand other complex object types.

Code example:

let original = { a: 1, b: new Date(), c: new Map([[1, 'one']]) };
let copy = structuredClone(original);

Applicable scenarios:

  • Complex objects need to be copied, includingMapSetAdvanced data structures.

4. Copying methods for special data types

1. ()

()Used to create a new object that inherits from the specified prototype object, rather than copying the properties of the original object.

Code example:

let person = { name: "Alice", age: 25 };
let newPerson = (person);

Applicable scenarios:

  • Used for prototype inheritance, not just copying.

2. Copying of Map and Set

MapandSetProvides direct constructors that can create shallow copies of them.

Code example:

let originalMap = new Map([[1, 'one']]);
let copyMap = new Map(originalMap);

Applicable scenarios:

  • Need to copyMaporSetWhen it is suitable for shallow copying operations.

5. Freeze the object: prevent object modification

Although it is not a copy method,()It can prevent the object's properties from being modified. This is a shallow freeze, and nested objects can still be modified.

Code example:

let obj = { name: "Alice", details: { age: 25 } };
(obj);

Applicable scenarios:

  • It is especially suitable for configuring or constant objects when it is necessary to prevent objects from being modified.

6. Summary and best practices

In JavaScript, different replication methods are suitable for different scenarios. Here is a summary:

  • Reference assignment: Efficient, has little memory usage, but it will have side effects, suitable for data sharing.
  • Light copy: Suitable for simple objects or arrays, with good performance, but cannot handle deep nested objects.
  • Deep copy: Suitable for complete replication of complex objects, ensuring data independence, but with high performance overhead.
  • Copying of special data types:againstMapSetDateChoose the appropriate copy method.
  • Freeze the object: Suitable for scenarios where objects need to be ensured that objects are not modified, such as configuration files or constants.

In actual projects, choosing the right copy method can greatly improve the efficiency and maintainability of the code. Deeply understanding the applicable scenarios of these methods for different needs can help you write more robust and maintainable code.

Through this article, we have sorted out various methods and application scenarios in JavaScript from reference assignment to deep copy. During the development process, we need to flexibly choose the appropriate method to ensure effective management and efficient processing of data.

The above is the detailed content of several common copying methods for JavaScript objects and arrays. For more information about copying JavaScript objects and arrays, please pay attention to my other related articles!