ES6展開運算符

語法

  • 用於函數調用javascript

    myFunction(...iterableObj);
  • 用於數組字面量java

    [...iterableObj, 4, 5, 6]

函數傳參

目前爲止,咱們都是使用Function.prototype.apply方法來將一個數組展開成多個參數:es6

function myFunction(x, y, z) { }
var args = [0, 1, 2];
myFunction.apply(null, args);

使用es6的展開運算符能夠這麼寫:spring

function myFunction(x, y, z) { }
var args = [0, 1, 2];
myFunction(...args);
  • 選擇性傳參數組

    function filter(type, ...items) {
        return items.filter(item => typeof item === type);
    }
    filter('boolean', true, 0, false);        // => [true, false]
    filter('number', false, 4, 'Welcome', 7); // => [4, 7]

還能夠同時展開多個數組:app

function myFunction(v, w, x, y, z) { }
var args = [0, 1];
myFunction(-1, ...args, 2, ...[3]);

數據解構

let cold = ['autumn', 'winter'];
let warm = ['spring', 'summer'];
// 析構數組
let otherSeasons, autumn;
[autumn, ...otherSeasons] = cold;
otherSeasons      // => ['winter']

數據構造

  • 兩個對象鏈接返回新的對象函數

    let a = {aa:'aa'}
    let b = {bb:'bb'}
    let c = {...a,...b}
    console.log(c)
    // {"aa":"aa","bb":"bb"}
  • 兩個數組鏈接返回新的數組prototype

    let d = ['dd']
    let e = ['ee']
    let f = [...d,...e]
    console.log(f)
    // ["dd","ee"]
    • 在中間插入數組code

      var parts = ['shoulder', 'knees'];
      var lyrics = ['head', ...parts, 'and', 'toes']; // ["head", "shoulders", "knees", "and", "toes"]
    • 在尾部插入數組對象

      // ES5
      var arr1 = [0, 1, 2];
      var arr2 = [3, 4, 5];
      // 將arr2中的全部元素添加到arr1中
      Array.prototype.push.apply(arr1, arr2);
      
      // ES6
      var arr1 = [0, 1, 2];
      var arr2 = [3, 4, 5];
      arr1.push(...arr2);
  • 數組加上對象返回新的數組

    let g = [{gg:'gg'}]
    let h = {hh:'hh'}
    let i = [...g,h]
    console.log(i)
    // [{"gg":"gg"},{"hh":"hh"}
  • 數組+字符串

    let j = ['jj']
    let k = 'kk'
    let l = [...j,k]
    console.log(l)
    // ["jj","kk"]
  • 帶有數組和對象的結合

    let state = {
        resultList: [],
        currentPage: 0,
        totalRows: {}
    }
    let data = {
        resultList: [{new:'new'}],
        currentPage: 2,
        totalRows: {row:'row'}
    }
    let combile = {
                    ...state,
                    resultList: [
                        ...state.resultList,
                        ...data.resultList
                    ],
                    currentPage: data.currentPage,
                    totalRows: data.totalRows
                }
    console.log(combile)
    // {"resultList":[{"new":"new"}],"currentPage":2,"totalRows":{"row":"row"}}
相關文章
相關標籤/搜索