The learning mainly comes from the tutorial of Mr. Ruan Yifeng. Invasion and deletion.
meaning
The spread operator (spread) is three dots ( ...
). It's like the inverse of the rest parameter, turning an array into a comma-separated sequence of parameters.
Take a look at the difference:
1、
2. Function call
function add(x, y) {
return x + y;
}
const numbers = [4, 38];
add(...numbers)
If we usually pass parameters, we will definitely call add(numbers[0],numbers[1]) like this
function f(v, w, x, y, z) { }
const args = [0, 1];
f(-1, ...args, 2, ...[3]);
Very flexible to use
Note that the spread operator can be placed in parentheses only when the function is called, otherwise an error will be reported.
(...[1, 2])
// Uncaught SyntaxError: Unexpected number
console.log((...[1, 2]))
// Uncaught SyntaxError: Unexpected number
console.log(...[1, 2])
// 1 2
! ! Alternative to the apply method of a function
Since the spread operator expands the array, there is no need for a apply
method to turn the array into a function parameter.
// ES5 的写法
function f(x, y, z) {
// ...
}
var args = [0, 1, 2];
f.apply(null, args);
// ES6的写法
function f(x, y, z) {
// ...
}
let args = [0, 1, 2];
f(...args);
push
Adds an array to the end of another array with a function .
// ES5的 写法
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
Array.prototype.push.apply(arr1, arr2);
// ES6 的写法
let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];
arr1.push(...arr2);
! Application of spread operator
(1) Copy the array
Arrays are composite data types. If you copy directly, you just copy the pointer to the underlying data structure, instead of cloning a brand new array.
const a1 = [1, 2];
const a2 = a1;
a2[0] = 2;
a1 // [2, 2]
In the above code, it is a2
not a1
a clone, but another pointer to the same data. Modifications a2
will directly lead a1
to changes.
ES5 can only use workarounds to copy arrays
const a1 = [1, 2];
const a2 = a1.concat();
a2[0] = 2;
a1 // [1, 2]
In the above code, a1
a clone of the original array will be returned, and modification a2
will not have any a1
effect.
The spread operator provides a shorthand for copying an array.
const a1 = [1, 2];
// 写法一
const a2 = [...a1];
// 写法二
const [...a2] = a1;
(2) Merge arrays
The spread operator provides a new way of combining arrays.
const arr1 = ['a', 'b'];
const arr2 = ['c'];
const arr3 = ['d', 'e'];
// ES5 的合并数组
arr1.concat(arr2, arr3);
// [ 'a', 'b', 'c', 'd', 'e' ]
// ES6 的合并数组
[...arr1, ...arr2, ...arr3]
// [ 'a', 'b', 'c', 'd', 'e' ]
However, these two methods are shallow copies, and you need to be careful when using them.
const a1 = [{ foo: 1 }];
const a2 = [{ bar: 2 }];
const a3 = a1.concat(a2);
const a4 = [...a1, ...a2];
a3[0] === a1[0] // true
a4[0] === a1[0] // true