ES6展开运算符

发布时间:2019-08-20 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了ES6展开运算符脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

语法

函数传参

目前为止,我们都是使用Function.prototype.apply方法来将一个数组展开成多个参数:

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

使用es6的展开运算符可以这么写:

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]

还可以同时展开多个数组:

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"}
  • 两个数组连接返回新的数组

    let d = ['dd']
    let e = ['ee']
    let f = [...d,...e]
    console.log(f)
    // ["dd","ee"]
    • 在中间插入数组

      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"}}

脚本宝典总结

以上是脚本宝典为你收集整理的ES6展开运算符全部内容,希望文章能够帮你解决ES6展开运算符所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。