1. Use the spread operator to expand the array
console.log(...[1,2,3,4,5]) // 1 2 3 4 5
let arr = [
...(x > 0 ? [1,2,3]: [4,5,6]),
7,8,9
]
[...[]] // []
[...[], 1] // [1]
2. The spread operator can be used to pass function parameters, rest parameters
function aaa(x, ...rest){
console.log(rest); // [2,3,5,6]
}
aaa(1,...[2,3], 5, 6)
3. Use the spread operator instead of the apply method
// 运用场景1:函数传参
function x(x, y, z) {
}
let arr = [1,2,3]
x.apply(null, arr) // 可以使用 x(...arr) 直接代替
x(...arr)
// 运用场景2:Math.max()
Math.max.apply(null, [1,2,3,4]) // 4
Math.max(...[1,2,3,4]) // 4
Math.max(1,2,3,4) // 4
// 运用场景3:数组 push
let rr1 = [1,2,3]
let rr2 = [4,5,6]
Array.prototype.push.apply(rr1, rr2)
console.log(rr1) //[1, 2, 3, 4, 5, 6]
console.log(rr1.push(...rr2)) // [1, 2, 3, 4, 5, 6] -> 作用相当于Array.prototype.push.apply(rr1, rr2)
4. Use the spread operator to copy the array
let a = [1,2,3]
let b = [...a] // [1,2,3]
let [...c] = a // [1,2,3]
b[0] = 1111
c[0] = 222
console.log(a) // [1, 2, 3]
console.log(b) // [1111, 2, 3]
console.log(c) // [222, 2, 3]
5. Use the spread operator to merge arrays
let a1 = [1,2]
let a2 = [3,4]
let a3 = [5,6]
let res1 = a1.concat(a2).concat(a3) // 浅拷贝
let res2 = [...a1, ...a2, ...a3] // 浅拷贝
6. Use in conjunction with destructuring assignment
let a = [1,2,3,4]
let [x, ...rest] = a // x->1 rest->[2,3,4]
7. Use with strings
[...'hello'] // ['h', 'e', 'l', 'l', 'o']
8. The spread operator is used in conjunction with the Map, Set and Generate functions
let map = new Map([['222', 222],[true, 1], [false, 0], ['aaa', 'a']])
let keys = [...map.keys()] // ['222', true, false, 'aaa']
let arr = [1,2,3,4]
let set = new Set([...arr])
let go = function*() {
yield 1;
yield 2;
yield 3;
}
[...go()] // [1,2,3]
Just record this, I wish you all a happy!