JavaScript ES6中的简写语法总结与使用技巧(9)
下面我们继续来讲讲spread和rest操作符。
剩余参数和拓展符
ES6之前,对于不确定数量参数的函数。你需要使用伪数组arguments,它拥有length属性,却又不具备很多一般数组有的特性。需要通过Array#slice.call转换arguments对象真数组后才能进行下一步的操作:
function join() {
var list = Array.prototype.slice.call(arguments)
return list.join(', ')
}
join('first', 'second', 'third')
// <- 'first, second, third'
对于这种情况,ES6提供了一种更好的解决方案:rest。
剩余参数rest
使用rest, 你只需要在任意JavaScript函数的最后一个参数前添加三个点...即可。当rest参数是函数的唯一参数时,它就代表了传递给这个函数的所有参数。它起到和前面说的.slice一样的作用,把参数转换为了数组,不需要你再对arguments进行额外的转换了。
function join(...list) {
return list.join(', ')
}
join('first', 'second', 'third')
// <- 'first, second, third'
rest参数之前的命名参数不会被包含在rest中,
function join(separator, ...list) {
return list.join(separator)
}
join('; ', 'first', 'second', 'third')
// <- 'first; second; third'
在箭头函数中使用rest参数时,即使只有这一个参数,也需要使用圆括号把它围起来,不然就会报错SyntaxError,使用示例如下:
var sumAll = (...numbers) => numbers.reduce( (total, next) => total + next ) console.log(sumAll(1, 2, 5)) // <- 8
上述代码的ES5实现如下:
// ES5的写法
function sumAll() {
var numbers = Array.prototype.slice.call(arguments)
return numbers.reduce(function (total, next) {
return total + next
})
}
console.log(sumAll(1, 2, 5))
// <- 8
拓展运算符
拓展运算符可以把任意可枚举对象转换为数组,使用拓展运算符可以高效处理目标对象,在拓展目前前添加...就可以使用拓展运算符了。下例中...arguments就把函数的参数转换为了数组字面量。
function cast() {
return [...arguments]
}
cast('a', 'b', 'c')
// <- ['a', 'b', 'c']
使用拓展运算符,我们也可以把字符串转换为由每一个字母组成的数组:
[...'show me'] // <- ['s', 'h', 'o', 'w', ' ', 'm', 'e']
使用拓展运算符,还可以拼合数组:
function cast() {
return ['left', ...arguments, 'right']
}
cast('a', 'b', 'c')
// <- ['left', 'a', 'b', 'c', 'right']
var all = [1, ...[2, 3], 4, ...[5], 6, 7]
console.log(all)
// <- [1, 2, 3, 4, 5, 6, 7]
内容版权声明:除非注明,否则皆为本站原创文章。
