- 擴展運算符
擴展運算符(spread)是三個點(...)。它好比 rest 參數(shù)的逆運算,將一個數(shù)組轉(zhuǎn)為用逗號分隔的參數(shù)序列。
console.log(1, ...[2, 3, 4], 5) // 1 2 3 4 5
function add(x, y) {
return x + y
}
const numbers = [4, 38]
// 擴展運算符,將傳入的數(shù)組變?yōu)閰?shù)序列
console.log(add(...numbers)) // 42
console.log(add.apply(null, numbers)) // 42
- 替代apply方法
function add(x, y) {
return x + y
}
const numbers = [4, 38]
// ES6寫法
console.log(add(...numbers)) // 42
// ES5寫法
console.log(add.apply(null, numbers)) // 42
console.log(Math.max.apply(null, [14, 2, 77])) // 77
console.log(Math.max(...[14, 2, 77])) // 77
console.log(Math.max(14, 2, 77)) // 77
擴展運算符的應(yīng)用
- 復(fù)制數(shù)組
var a1 = [1, 2]
var a2 = [...a1]
a1[0] = 2
console.log(a1); // [2,2]
console.log(a2) // [1,2]
- 合并數(shù)組
const arr1 = ['a', 'b']
const arr2 = ['c']
const arr3 = ['d', 'e']
console.log(arr1.concat(arr2, arr3)) // [ 'a', 'b', 'c', 'd', 'e' ]
console.log([...arr1, ...arr2, ...arr3]) // [ 'a', 'b', 'c', 'd', 'e' ]
- 與解構(gòu)賦值結(jié)合
const [first, ...rest] = [1, 2, 3, 4, 5]
console.log(first, rest) // 1 [ 2, 3, 4, 5 ]
- 字符串
console.log([...'Hello']) // [ 'H', 'e', 'l', 'l', 'o' ]
- Map、Set和Generator函數(shù)
具有 Iterator 接口的對象,都可以使用擴展運算符
let map = new Map([[1, 'one'], [2, 'two'], [3, 'three']])
console.log([...map.keys()])
const set = new Set([1, 2, 3, 4])
console.log(...set)
var foo = function*() {
yield 1
yield 2
yield 3
}
console.log(...foo())