擴展運算符用三個點號表示,功能是把數組或類數組對象展開成一系列用逗號隔開的值數組
var foo = function(a, b, c) { console.log(a); console.log(b); console.log(c); } var arr = [1, 2, 3]; //傳統寫法 foo(arr[0], arr[1], arr[2]); //使用擴展運算符 foo(...arr); //1 //2 //3
特殊應用場景:app
//數組深拷貝 var arr2 = arr; var arr3 = [...arr]; console.log(arr===arr2); //true, 說明arr和arr2指向同一個數組 console.log(arr===arr3); //false, 說明arr3和arr指向不一樣數組 //把一個數組插入另外一個數組字面量 var arr4 = [...arr, 4, 5, 6]; console.log(arr4);//[1, 2, 3, 4, 5, 6] //字符串轉數組 var str = 'love'; var arr5 = [...str]; console.log(arr5);//[ 'l', 'o', 'v', 'e' ]
rest運算符也是三個點號,不過其功能與擴展運算符剛好相反,把逗號隔開的值序列組合成一個數組函數
//主要用於不定參數,因此ES6開始能夠再也不使用arguments對象 var bar = function(...args) { for (let el of args) { console.log(el); } } bar(1, 2, 3, 4); //1 //2 //3 //4 bar = function(a, ...args) { console.log(a); console.log(args); } bar(1, 2, 3, 4); //1 //[ 2, 3, 4 ]
rest運算符配合解構使用: var [a, ...rest] = [1, 2, 3, 4]; console.log(a);//1 console.log(rest);//[2, 3, 4]
對於三個點號,三點放在形參或者等號左邊爲rest運算符; 放在實參或者等號右邊爲spread運算符,或者說,放在被賦值一方爲rest運算符,放在賦值一方爲擴展運算符。rest