在ES6中。 三个点(…) 有2个含义,分别表示 扩展运算符 和 剩余运算符。
用法一:将数组扩展成函数参数
function foo(a,b, c) {
console.log(a);//1
console.log(b);//2
console.log(c)//3
}
var arr = [1,2,3]
foo(...arr)
用法二:数组合并
var arr1 = [1,2,3], arr2 = [4,5,6];
var arr3 = [...arr1, ...arr2] // arr3为[1, 2, 3, 4, 5, 6]
或者
var arr1 = [1,2,3], arr2 = [4,5,6];
arr1.push(...arr2) // arr1为[1, 2, 3, 4, 5, 6]
用法三:字符串转数组
var str = 'zyp';
var strArr = [...str] //strArr为["z", "y", "p"]
用法四:将类数组对象转化成数组
function foo() {
var argArr = [...arguments]
console.log(argArr) //[1,2,3,4]
console.log(argArr instanceof Array) //true
}
foo(1,2,3,4)
用法一:用于定义重载的函数
function foo(...arr) {
console.log(arr) //[1,2,3,4]
console.log(arr instanceof Array) // true
}
foo(1,2,3,4)
用法二:数组和对象的解构
var [a, ...restArr] = [1,2,3,4]
var {name: n, ...restObj} = {name: 'zyp', age: 18, like: 'sleep'}
console.log(restArr) //[2,3,4]
console.log(restObj)//{age: 18, like: 'sleep'}