展開運算符(spread operator) ES6中“...”的作用之一是,展開運算符。 顧名思義,它的作用是把某些結合數據展開。 在Array、Object、Set和Map上都可以使用。 剩餘操作符(rest operator) 另一種作用是 用於解構,意思是把剩餘的東西放到一個array里,並 ...
展開運算符(spread operator)
ES6中“...”的作用之一是,展開運算符。
顧名思義,它的作用是把某些結合數據展開。
在Array、Object、Set和Map上都可以使用。
//array
let a = [1,2,3];
let b= [0,...a,4]; // b=[0,1,2,3,4]
//object
let obj = {a:1,b:2};
let obj1 = {...obj,c:3}; // {a:1, b:2 , c:3}
//set
let set = new Set([1,2,3]);
let set2 = new Set([...set,3,4]); // Set(4)[1,2,3,4]
//map
let map = new Map([['a',2],['b',3]]);
let map1 = new Map([['c',3],...map]); //Map(3) {"c" => 3, "a" => 2, "b" => 3}
剩餘操作符(rest operator)
另一種作用是 用於解構,意思是把剩餘的東西放到一個array里,並賦值給 【...變數】。
let a = [1,2,3,4];
let [b,...c] = a;
console.log(b); //1
console.log(c); //[2,3,4]
/*--------------------------*/
let a = [1,2,3];
//b = 1
//然後剩下的2,3以[2,3]的形式賦值給[c,d,e]
let [b,...[c,d,e]] = a;
b //1
c //2
d //3
e //undefined