...Rest参数和扩展运算符
Rest 参数
在写函数的时候,部分情况我们不是很确定参数有多少个,比如求和运算,之前都是这么做的:
ES5中的求和运算(使用arguments对象)
function sum() {
let num = 0
Array.prototype.forEach.call(arguments, function(item) {
num += item * 1
})
return num
}
console.log(sum(1, 2, 3)) // 6
console.log(sum(1, 2, 3, 4)) // 10
其实在上面说过,这个代码在 ES5 中可以这么写,在 ES6 就不能这么写了,因为 arguments 的问题。现在需要这样写:
ES6中的求和运算
function sum(...nums) {