ES6_剩余参数‘...’创建可变数量参数函数 && 扩展操作符‘...’的使用

《剩余参数‘...’》

In order to help us create more flexible functions, ES6 introduces the rest parameter for function parameters.

为了帮助我们创建更灵活的函数,ES6为函数参数引入了rest参数。

function howMany(...args) {
  return "You have passed " + args.length + " arguments.";
}
console.log(howMany(0, 1, 2)); //You have passed 3 arguments.
console.log(howMany("string", null, [1, 2, 3], { })); //You have passed 3 arguments.

 

With the rest parameter, you can create functions that take a variable number of arguments. These arguments are stored in an array that can be accessed later from inside the function.

使用剩余参数,可以创建具有可变数量参数的函数。这些参数存储在一个数组中,以后可以从函数内部访问。

The rest parameter eliminates the need to check the args array and allows us to apply map(), filter() and reduce() on the parameters array.

剩余参数消除了检查args数组的需要,并允许我们对参数数组应用map()、filter()和reduce()。

再如:

 

/*
const sum = (x, y, z) => {
  const args = [x, y, z];
  return args.reduce((a, b) => a + b, 0);
}
*/

const sum=(...n)=>{
  return n.reduce((a1,a2)=>a1+a2,0);
}

//测试:
console.log(sum(2,2,2,2,2)); //10

 

 

《扩展操作符‘...’的使用》

下面的例子,目的是把arr1里的数据复制一份给arr2。由于扩展操作符会把对象(包括数组)拆分成以逗号分开的内容,

故直接将[...arr1]赋给arr2既可。

const arr1 = ['JAN', 'FEB', 'MAR', 'APR', 'MAY'];
let arr2;

arr2 = [...arr1];  // 这样既可

console.log(arr2); //[ 'JAN', 'FEB', 'MAR', 'APR', 'MAY' ]

Math.max() expects comma-separated arguments, but not an array. 

Math.max()里需要逗号分隔的参数,不是数组。

ES5中求数组中元素的最大值:

var arr = [6, 89, 3, 45];
var maximus = Math.max.apply(null, arr); //89

上面必须要用Math.max.apply(null, arr), 如果用 Math.max(arr) 只会返回 NaN,因为Math.max()里需要逗号分隔的参数,而不是数组。

而由于扩展操作符会把对象(包括数组)拆分成以逗号分开的内容,故在ES6中可以把上面代码替换成:

ES6中求数组中元素的最大值:

const arr = [6, 89, 3, 45];
const maximus = Math.max(...arr); //89

 ‘...’只能用在函数参数体内和数组中,否则会报错!

 

posted @ 2022-09-13 20:07  枭二熊  阅读(766)  评论(0编辑  收藏  举报