学习内容:
-
...
- 扩展运算符:把数组或类数组展开成用逗号分隔的值
- rest参数:把逗号隔开的值组成一个数组
扩展运算符
...如果放在等号的左边,或在形参上就是rest参数,
如果...在等号右边,或在实参上就是扩展运算符
使用场景1:
// 前面学习过解构赋值,但下面这种形式不是解构
// 解构要求两边形式完全一样,如果要改成解构赋值
// 需要把函数test的参数也改成数组[a,b,c],
// 但这就和原始需求不一致了
function test(a, b, c) {
console.log(a,b,c)
}
let arr = [1,2,3]
test(arr)
------------------------------
[1, 2, 3] undefined undefined
使用“...”扩展运算符把数组展开成用逗号分隔的值
注意:
定义了遍历器接口的对象才能使用扩展运算符转化为数组。
类数组没有部署 Iterator 接口所以扩展运算符会报错。
// 扩展运算符的应用
function test(a, b, c) {
console.log(a,b,c)
}
let arr = [1,2,3]
test(...arr) // 注意这里...
--------------------------------
1 2 3
使用场景2:
ES5数组的合并
let arr1 = [1,2,3]
let arr2 = [4,5,6]
// ES5当中把两个数组合并为一个,除了写循环再push,
// 注意push只能push值,不能push数组
// 也可以使用下面的代码合并
Array.prototype.push.apply(arr1,arr2)
console.log(arr1)
----------------------
(6) [1, 2, 3, 4, 5, 6]
ES6数组的合并
let arr1 = [1,2,3]
let arr2 = [4,5,6]
arr1.push(...arr2)
console.log(arr1)
-----------------------------
(6) [1, 2, 3, 4, 5, 6]
使用场景3:
把字符串转为数组
let str = 'imooc'
var arr = [...str]
console.log(arr)
------------------------------
(5) ['i', 'm', 'o', 'o', 'c']
使用场景4:
对不确定参数的求和
ES5写法:
function test(x, y, z) {
// console.log(arguments)
let sum = 0
Array.prototype.forEach.call(arguments, function (item) {
sum += item
})
return sum
}
console.log(test(1, 2))
console.log(test(1, 2, 3))
-------
3
6
function test(x, y, z) {
// console.log(arguments)
let sum = 0
// Array.prototype.forEach.call(arguments, function (item) {
// sum += item
// })
Array.from(arguments).forEach(function (item) { // ES6把类数组转为数组的写法
sum += item
})
return sum
}
console.log(test(1, 2))
console.log(test(1, 2, 3))
ES6写法:
使用...rest参数
function test(...args) { // 注意这里就是rest参数
console.log(args)
let sum = 0
args.forEach(function(item) {
sum += item
})
return sum
}
console.log(test(1, 2))
console.log(test(1, 2, 3))
----------------------------------
(2) [1, 2]
3
(3) [1, 2, 3]
6
下面这个例子,x参数一定会传,其它的参数不会传,也就是说剩下的参数...args全管了,也就是理解为剩余参数
function test(x, ...args) {
console.log(x)
console.log(args)
}
test(1, 2, 3)
test(1, 2, 3, 4)
--------------------------
1
(2) [2, 3]
1
(3) [2, 3, 4]
使用场景5:
与解构联合使用
let [x, ...y] = [1, 2, 3]
console.log(x)
console.log(y)
-----------------
1
(2) [2, 3]