ES6扩展运算符使用。
1.基本使用
数组
let arr = [1,2,3,4,5]; let arr2 = [...arr]; console.log(arr2); //[ 1, 2, 3, 4, 5 ] console.log(arr2 == arr); //false
对象
let obj = {a:1,b:2}; let obj2 = {...obj}; console.log(obj2); //{ a: 1, b: 2 } console.log(obj == obj2); //false
字符串转数组
let str = "hello"; let str2 = [...str]; console.log(str2); //[ 'h', 'e', 'l', 'l', 'o' ]
2.函数传值;
function fn(a,b,c){ console.log(a) console.log(b) console.log(c) } let arr = [1,2,3]; //ES5 // fn(arr[0],arr[1],arr[2]); // fn.apply(null,arr); //ES6 fn(...arr); // 1 2 3
3.数组拷贝
let arr = [1,2,3,4]; let arr2 = [...arr]; arr2.push(5); console.log(arr); //[ 1, 2, 3, 4 ] console.log(arr2); //[ 1, 2, 3, 4, 5 ] console.log(arr == arr2); //false
4.对象拷贝
let obj = {a:1,b:2}; let obj2 = {...obj}; obj2.c = 3; console.log(obj); //{ a: 1, b: 2 } console.log(obj2); //{ a: 1, b: 2, c: 3 } console.log(obj == obj2); //false
5.代替数组的unshift方法
let arr = [1,2,3]; let arr2 = [4,5,...arr]; console.log(arr); //[ 1, 2, 3 ] console.log(arr2); [ 4, 5, 1, 2, 3 ] console.log(arr == arr2); false
6.代替数组的push方法
let arr = [1,2,3]; let arr2 = [...arr,4,5,"a",null,undefined,function(){},Symbol]; console.log(arr); //[ 1, 2, 3 ] console.log(arr2); [ 1, 2, 3, 4, 5, 'a', null, undefined, [Function], [Function: Symbol] ] console.log(arr == arr2); //false
7.配合解构使用
数组
let [a,...arr] = [1,2,3,4,5]; console.log(a); //1 console.log(arr); //[ 2, 3, 4, 5 ]
对象
let {a,...obj} = {a:1,b:"1",c:function(){},d:null,e:undefined,e:Symbol}; console.log(a); //1 console.log(obj); //{ b: '1', c: [Function: c], d: null, e: [Function: Symbol] }
8.总结
放在被赋值一方为rest运算符,放在赋值一方为扩展运算符