JavaScript Expansion Operator and Application of Instance Code

  • 2021-10-24 18:43:20
  • OfStack

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


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

The above usage is actually equivalent to


obj2 = {value1: 1, value2: 2}

The expansion operator is written in the same way as the obj2 = obj1 The difference between the writing of direct assignment is that if you assign directly, for 引用类型 For example, it is equivalent to just assigning values obj1 The memory space address of the obj2 When things change, obj1 Will change with it. Instead, use 展开运算符 Writing, because obj1 The property types in the object are all 基本类型 Equivalent to recreating 1 object, at which point obj2 When there is a change, it will not affect obj1 This object. But only if the attributes are of basic type (or only 1 layer of deep copy). If the property in the object has a reference type, if you modify the value of the reference type in the property, the property 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;

console.log('obj1:', obj1);
console.log('obj2:', obj2);

Application of Expansion Operator

1. Use the expansion operator in a function


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

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

2. Using expansion operators in array literals


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

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

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


//  Expansion operators in deconstruction assignments can only be used at the end. 
let [a, b, ...c] = [1, ,2, 3, 4]
console.log(a, b, c) // 1, 2, [3, 4]

4. Class arrays become arrays


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

5. Use the Expansion Operator in an Object
The object expansion operator in ES7 allows us to manipulate objects more quickly:


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

Insert one object into another object:


let z={a:3,b:4};
let n={x:1,y:2,...z};
console.log(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};
console.log(ab); // {x:1,y:2,z:3}

Related articles: