扩展运算符是三个点(…)。它好比 rest 参数的逆运算,将一个数组转为用逗号分隔的参数序列。
1. 先看看es5与es6的写法区别
const arr1 = [1,2] const arr2 = [5,6,6] const newarr1 = [1,4,5] //es5语法数组合并 // const arr3 = arr1.concat(arr2,newarr1) // console.log(arr3)//(8) [1, 2, 5, 6, 6, 1, 4, 5] //es6语法数组合并 const arr3 = [...arr1,...arr2,...newarr1] console.log(arr3)//(8) [1, 2, 5, 6, 6, 1, 4, 5] //注:两种方法均为浅拷贝
const arr1 = [1,2] const arr2 = [5,6,6] //es5语法添加返回并数组长度 // const arr3 = Array.prototype.push.apply(arr1,arr2)//5 //es6语法添加返回并数组长度 console.log(arr1.push(...arr2))//5
2.学习es6拓展运算符语法使用的好处
//将字符串转为数组 const arr1 = 'abcde' const arr2 = [...arr1] console.log(arr2)//(5) ["a", "b", "c", "d", "e"]
//扩展运算符将数组转化为参数序列 function fun(x,y){ return x+y } const args = [1,3] console.log(fun(...args))//4
//配合解构赋值的使用 const [a1,...a2] = [1,2,3,4,5] console.log(a1)//1 console.log(a2)//(4) [2, 3, 4, 5] //注:扩展运算符不能放在数组的第一位