ES6 引入了一个新的运算符 …,通常称为 spread 或 rest(展开或收集)运算符,取决于它在哪 / 如何使用。
-
用在数组(实际上是任何iterable)之前,把这个变量展开为各个独立的值
function foo (x, y, z) { console.log(x, y, z) } foo(...[1, 2, 3]) // 1 2 3 // 替代之前ES6之前apply(..)的写法 foo.apply(null, [1, 2, 3]) // 1 2 3
-
可以在上下文中用来展开 / 拓展一个值
var a = [2, 3, 4] var b = [1, ...a, 5] // 基本上替代了concat(..) console.log(b) // [ 1, 2, 3, 4, 5 ]
-
收集剩余参数
-
在函数声明中的 gather/rest 用法
function rest (x, y, ...z) { console.log(x, y, z) } rest(1, 2, 3, 4, 5) // 1 2 [ 3, 4, 5 ]
function rest_all (...rest) { // rest已经是一个收集所有参数,真正的数组,为类数组对象arguments提供了一个非常可靠的替代形式 console.log(rest) // ...rest [ 1, 2, 3, 4, 5 ] console.log(...rest) // 展开 1 2 3 4 5 rest.shift() // 使用数组方法 // 替代ES6之前把arguments转换为一个真正的数组 var args = Array.prototype.slice.call(arguments) console.log(args) // [ 1, 2, 3, 4, 5 ] console.log(arguments) // [Arguments] { '0': 1, '1': 2, '2': 3, '3': 4, '4': 5 } } rest_all(1, 2, 3, 4, 5)
-
在解构赋值中 用法
var a = [2, 3, 4] var [b, ...c] = a console.log(b, c) // 2 [ 3, 4 ] 收集剩余的值