根据问题的标题,在函数声明(括号内)中使用 ... 是 rest operator 或 rest参数,为了帮助我们创建更灵活的函数,ES6引入了函数参数的rest参数。
使用其余参数,您可以创建带有可变数量参数的函数。这些参数存储在一个数组中,以后可以从函数内部访问。
示例:1
function foo(...args) {
return "You have passed " + args.length + " arguments.";
}
console.log(foo(0, 1, 2,4)); // You have passed 4 arguments.
console.log(foo("hello", null, [1, 2], { })); // You have passed 4 arguments.
示例 2:
function foo(...args){
args.forEach(function(arg){
console.log(arg);
})
}
foo(2,3,4,5,6);
rest 参数消除了检查args 数组的需要,并允许我们在参数数组上应用map()、filter()、reduce() 和其他数组高阶函数。
...运算符的其他用例:
-
用作spread operator,与rest operator相反。
const arr = [6, 89, 3, 45];
const maximum= Math.max(...arr);
console.log(maximum);
-
... 运算符用于非常轻松地复制数组或对象,并且分别在 javascript 框架和库(如 angular 和 react)中非常有用。
const arr1 = [1,2,3,4];
const arr2 = [...arr1];
console.log(arr2);// [1,2,3,4];
const obj1 = {
name:'john',
age:25
}
const obj2 = {...obj1};
console.log(obj2); // Now obj2 is new object and is copy of obj1 (non-mutated
way)