Spread operator … (array)
The spread operator can split an array or array-like structure into a comma-separated sequence of arguments.
1
2const arr = [1, 2, 3];
console.log(...arr) //result is 1 2 3Note that the spread operator unpacks [ ] not a value, but a sequence. That is, something like
var a =...obj;
is wrong, because there is no such thing asvar a = 1, 2, 3;
. But the spread operator can be used for destructuring assignments.
Use of spread operator:
Pass a sequence of arguments to a function
1
2
3
4
5
6let arr = [1, 2, 3];
function getMax(a, b, c){
console.log(b);
}
getMax(...arr);
Math.max(...arr);
Merging of arrays
1
2
3
4
5const arr1 = [1, 2];
const arr2 = [3, 4];
const arr3 = arr1.concat(arr2) //The merge method in ES5. The result is [1, 2, 3, 4]
const arr4 = [...arr, ...arr2] //The merge method in ES6. The result is [1, 2, 3, 4]
Copy of array
1
2
3const arr1 = [1, 2, 3, 4];
const arr2 = [...arr1];
console.log(arr2); //result is [1, 2, 3, 4]Note that if the elements in the array are reference type elements, then this copy is also a shallow copy. If not, it is a deep copy.
Convert pseudo array to real array
1
2const divs = document.querySelectorAll('div');
console.log(divs); //The result is an object because it is a pseudo-array.1
2
3const divs = document.querySelectorAll('div');
const divArr = [...divs];
console.log(divArr); //The result is a real array: [div, div, div]The arguments parameter can also be converted to a true array using this method. But since there are rest parameters, this method is unnecessary.
Spread operator … (object)
Merge two objects
1
2
3
4
5
6
7
8
9
10let obj1 = {
name:'Tom',
age:18
}
let obj2 = {
gender:'male',
hobby:'football'
}
let obj3 = {...obj1, ...obj2};
console.log(obj3) //result {name: 'Tom', age: 18, gender: 'male', hobby: 'football'}
Add attributes to element objects
Native JS approach
1
2
3
4
5
6
7
8
9
10
11var obj = {
'id':'Hello',
'className':'box',
'style':'width:200px; height:200px; background:red'
}
let app = document.getElementsByTagName('div')[0]
for(let key in obj){
app[key]=obj[key]
//app[key] is to be distinguished from app.key, [key] is a variable and .key is a property name. That is, app[key] is the key in the key-value pair.
//[key] of obj[key] is the value in the key-value pair. It's not the key because the obj object is in the for in loop.
}
Spread operator method
1
2
3
4
5
6
7var obj = {
'id':'Hello',
'className':'box',
'style':'width:200px; height:200px; background:red'
}
let app = document.getElementsByTagName('div')[0]
app.innerHTML="<div "+...obj+"></div>" //Note here...obj can only be used in React.