SoFunction
Updated on 2025-04-09

Expand operators and application example code in JavaScript

The spread operator allows an expression to expand somewhere. Expand operators can be used where multiple parameters (for function calls) or multiple elements (for array literals) or multiple variables (for deconstructing assignments).

let obj1 = {
 value1: 1,
 value2: 2
};
let obj2 = {...obj1
};
(obj2); // {value1: 1, value2: 2}

The above usage is actually equivalent to

obj2 = {value1: 1, value2: 2}

How to write expansion operators andobj2 = obj1The difference between writing direct assignment is that if the assignment is directly,Reference TypeTo be honest, it's just an assignmentobj1memory space address, whenobj2When something changes,obj1It will also change with each other. Instead useExpand operatorIf you write it, becauseobj1The attribute types in the object areBasic Type, which is equivalent to recreating an object, at this timeobj2When changes occur, it will not affectobj1This object. But only if its properties are basic types (or only one deep copy is made). If the attribute in the object has a reference type, if the value of the reference type in the attribute is modified, the attribute values ​​of both objects will be modified.

let obj1 = {
 attri1: [3, 6, 0],
 attri2: 4,
 attri4: 5
};
let obj2 = {...obj1
};

obj2.attri2 = 888;
obj2.attri1[0] = 7;

('obj1:', obj1);
('obj2:', obj2);

Application of Expand Operators

1. Use the expand operator in the function

function test(a, b, c){};

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

2. Use expansion operators in array literals

let arr1 = [1, 2];
let arr2 = [...arr1, 3, 4]; // [1, 2, 3, 4]

// Use push methodlet arr1 = [1, 2];
let arr2 = [3. 4];
(...arr2); // [1, 2, 3, 4]

3. Used for deconstructing assignment. The expansion operator in deconstructing assignment can only be used at the end, otherwise an error will be reported.

// The expansion operator in the deconstructed assignment can only be used at the end.let [a, b, ...c] = [1, ,2, 3, 4]
(a, b, c) // 1, 2, [3, 4]

4. Class array becomes an array

let oLis = ("li");
let liArr = [...oLis];

5. Use expansion operators in objects
The object expansion operator in ES7 allows us to operate objects faster:

let {x,y,...z}={x:1,y:2,a:3,b:4};
x; // 1
y; // 2
z; // {a:3,b:4}

Insert an object into another object:

let z={a:3,b:4};
let n={x:1,y:2,...z};
(n); //{x:1,y:2,a:3,b:4}

Merge two objects:

let a={x:1,y:2};
let b={z:3};
let ab={...a,...b};
(ab); // {x:1,y:2,z:3}

This is the article about expanding operators and application example code in JavaScript. For more related js expanding operator content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!