拓展运算符

153 阅读1分钟

拓展运算符(...)能将数组解构为,隔开参数序列,也能将未定义的变量设置为数组

当用拓展运算符给数组赋值时,必须在参数的最后一位,否则报错
let [a,...b] = [1,2,3]         ==>  [2,3]
a = [1,2,3] console.log(...a)  ==>  1,2,3

注意: ...只有在函数调用时才能放到()中

(...[1,2,3])					Uncaught SyntaxError: Unexpected number
console.log((...[1,2,3]))		Uncaught SyntaxError: Unexpected number
console.log(...[1,2,3])			正确

替代Apply方法,解构数组

let arr = [1,2,3]
function buluohe() {
	some code
}
buluohe.apply(null, [arr])			
buluohe(...arr)						

替代conact方法,复制数组

let a1 = [1,2,3]
let a2 = a1.concat()				
let a2 = [...a1]		

替代conact方法,合并数组,注意这两种方法均为浅拷贝,修改了引用指向的值,会同步反映到新数组

let a1 = [1]
let a2 = [2,3]
let a3 = [4]
let a4 = a1.concat(a2,a3)

let a4 = [...a1,...a2,...a3]

...与解构赋值结合

let [a,...b] = []			此时b是数组
let [a,...b] = [,1]			此时b[1]

解构字符串

let a = [...'buluohe']

对拥有iterator接口的对象,都可以通过...转化为真正的数组