声明展开和剩余参数

 在ES5中,我们可以用apply()函数把数组转化为参数。为此,ES5有了展开运算符(...)。举例来说,考虑我们上一条声明的sum函数。可以执行如下代码来传入参数x,y,z。

let params = [3,4,5];

console.log(sum(...params));

 以上代码和下面的ES5代码效果是一样的。

console.log(sum.apply(undefined,params));

  在函数运算中,展开运算符(...)也可以代替arguments,当剩余函数使用。考虑如下这个例子。

function restParamaterFunction (x,y ...a){
return( (x+y) * a.length);
};
console.log(restParamaterFunction(1,2,"hello",true,7));

  以上代码和下面代码输出结果一样(同样输出9)

function restParamaterFunction (x,y){
var a =Array.prototype.slice.call(arguments,2);
return (x+y) * a.length;
}
console.log(restParamaterFunction()1,2,'hello',true,7)

  

原文地址:https://www.cnblogs.com/zqm0924/p/12830933.html