ES6之后 --- spread 或 rest 运算符

ES6 引入了一个新的运算符 …,通常称为 spread 或 rest(展开或收集)运算符,取决于它在哪 / 如何使用。

  1. 用在数组(实际上是任何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
    
  2. 可以在上下文中用来展开 / 拓展一个值

    var a = [2, 3, 4]
    var b = [1, ...a, 5] // 基本上替代了concat(..)
    console.log(b) // [ 1, 2, 3, 4, 5 ]
    
  3. 收集剩余参数

  • 在函数声明中的 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 ] 收集剩余的值
    
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值