rest参数
rest参数(形式为...变量名
)用来获取函数的多于参数。
length
属性不包括rest参数function add(...values) {
let sum = 0;
for (var val of values) {
sum += val;
}
return sum;
}
add(2, 5, 3) // 10
rest参数与arguments的比较
// arguments变量的写法
function sortNumbers() {
return Array.prototype.slice.call(arguments).sort();
}
// rest参数的写法
const sortNumbers = (...numbers) => numbers.sort();
Array.prototype.slice.call
将参数arguments转化成数组slice()
用来提取字符串// 报错
let getTempItem = id => { id: id, name: "Temp" };
// 不报错
let getTempItem = id => ({ id: id, name: "Temp" });
箭头函数与rest参数结合使用
const numbers = (...nums) => nums;
numbers(1, 2, 3, 4, 5)
// [1,2,3,4,5]
const headAndTail = (head, ...tail) => [head, tail];
headAndTail(1, 2, 3, 4, 5)
// [1,[2,3,4,5]]
箭头函数的注意事项
1.函数体内的this对象,就是定义时所在的对象,而不是使用时所在对象(全局对象)
2.因为箭头函数没有this对象所以不能当作构造函数,不能使用new命令
3.不能使用arguments对象,用rest代替
4.不能使用yield命令
原文:https://www.cnblogs.com/yuanchao-blog/p/10844660.html