REST参数-扩展运算符(三个点)...
function fn(...arg){ console.log(arg);//[1,2,3,4,5] console.log(...arg);//1,2,3,4,5}fn(1,2,3,4,5)复制代码
1.替换apply
扩展运算符可以展开数组,代替apply()
将数组转化为函数参数的需求。
//ES5Math.max.apply(null, [1, 3, 5]);//ES6Math.max(...[1, 3, 5]); 复制代码
2.合并数组
//ES5var arr1 = [8]var arr2 = [9,11,12,13]arr1.push(arr2);//[8,[9,11,12,13]]Array.prototype.push.apply(arr1,arr2);//[8,9,11,12,13]// ES6arr1.push(...arr2);console.log(arr1)//[8,9,11,12,13]//可以直接写var newArr = [...arr1, ...arr2]console.log(newArr)复制代码
3.结构赋值
var [a, ...b] = [2,3,4,5,6];console.log(a, b);//2 [3,4,5,6]var [c, ...d] = [2];console.log(c, d);//2 []var [...x,y] = [2,3,4,5,6];//Uncaught SyntaxError: Rest element must be last element复制代码
当扩展运算符用于数组赋值,只能放在参数的最后一位,否则会报错。
*对象的扩展运算符
var {a, b, ...c} = {a : 12, b : 23, d : 34, c : 345}//c ->{d:34,c:345}var obj = {name : 'coco'}var obj1 = {age : 27}var newObj = {...obj, ...obj1};var newObj1 = {obj, obj1};console.log(newObj);//{name: "coco", age: 27}console.log(newObj1);//{name: "coco"} {age: 27}复制代码
*把类数组转化为数组
var strArr = [...'kiwi']console.log(strArr)//["k","i","w","i"]复制代码
扩展运算符还解决了JavaScript 将 32 位 Unicode 字符,识别为 2 个字符的问题。