ES6 扩展运算符
ES6 數組相關
一、擴展運算符 …
將一個數組變為參數序列;可與正常的函數參數結合使用;擴展運算符后面也可以放表達式;如果擴展運算符后面是空數組,不產生任何結果。只有函數調用時,擴展運算符才可以放到圓括號里。
const array1 = []; const array2 = []; const arr = [1, 2, 3];function push(array, ...items) {array.push(...items);console.log(...(items + '1')); // 1, 2, 3 1 }push(array1, ...arr); // 1 , 2 , 3 1 push(array2, ...[]); // 1 --> 這個1是拼接的1console.log(array1); // [1, 2, 3] console.log(array2); // []apply 方法的第二個參數把數組轉換為函數的時候,有了擴展運算符,可以代替 apply 這個作用
function f(x, y, z) {// ... }// ES5 的寫法 var args = [0, 1, 2]; f.apply(null, args); // apply 第一個參數是 THIS 指向 // 第二個參數傳遞的是一個數組// ES6 的寫法 let args = [0, 1, 2]; f(...args);數組是復合數據類型,直接復制只是復制了數組的地址,沒有重新創建一個數組。擴展運算符可以提供復制數組的簡便方法。如果數組成員是對象,只能復制對象的引用,如果修改了新數組成員,會同步反映到原數組(淺拷貝)
const a1 = [1, 2]; const a2 = a1; // 這里只是復制了a1的地址a2[0] = 2; console.log(a1); [2, 2];// ES5 var a1 = a1.concat(); a2[0] = 2; console.log(a1); // [2, 2]// ES6擴展運算符方法 const a2 = [...a1]; // 寫法一 const [...a2] = a1; // 寫法二提供了數組合并的新寫法
const arr1 = ['a', 'b']; const arr2 = ['c']; const arr3 = ['d', 'e'];// ES5 的數組合并 arr1.concat(arr2, arr3); console.log(arr1); // ['a', 'b', 'c', 'd', 'e']// ES6 的數組合并 const result = [...arr1, ...arr2, ...arr3]; console.log(result); // ['a', 'b', 'c', 'd', 'e']擴展運算符可以與解構賦值結合生成數組,只能把擴展運算符放在最后,否則會報錯
const [first, ...rest] = [1, 2, 3, 4, 5]; console.log(first); // 1 console.log(rest); // [2, 3, 4, 5]const [first, ...middle, last] = [1, 2, 3, 4, 5]; // 報錯總結
- 上一篇: Debug下正常,而Release失败的
- 下一篇: 【转】程序debug正常release错