JS在函数中获取传入的多余参数

在ES5中, 可以用aplly()把数组转化为参数。 为此ES2015 有了展开运算符(…).

比如:

      let params = [1,5,4];
      function sum(x = 1, y = 2, z = 3) {
        return x + y + z;
      }
      console.log(sum(...params)); // => 10
      console.log(sum.apply(undefined, params)); // => 10

函数中,展开运算符(…) 也可以代替arguments, 当作剩余参数使用

function a(x, y, ...a) {
        return (x + y) * a.length;
}
// 与下面同理
function a(x, y) {
        var a = Array.prototype.slice.call(arguments, 2); // 从下标为2之后的传入参数
        console.log(a);
        return (x + y) * a.length;
}
console.log(a(1,2,'hello',true,2)); // =>9
      
function a(x, y, ...a) {
        return (x + y) * a[3];
}
console.log(a(1,2,'hello',true,2,5)); // => 15

获取传入的多余参数和传入多余参数使用实例就如上述代码

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值