• es6


    扩展运算符提供了复制数组的简便写法。

    const a1 = [1, 2];
    // 写法一
    const a2 = [...a1];
    // 写法二
    const [...a2] = a1;
    

      

    (2)合并数组

    扩展运算符提供了数组合并的新写法。
    
    const arr1 = ['a', 'b'];
    const arr2 = ['c'];
    const arr3 = ['d', 'e'];
    
    // ES5 的合并数组
    arr1.concat(arr2, arr3);
    // [ 'a', 'b', 'c', 'd', 'e' ]
    
    // ES6 的合并数组
    [...arr1, ...arr2, ...arr3]
    // [ 'a', 'b', 'c', 'd', 'e' ]
    

      

    const a1 = [{ foo: 1 }];
    const a2 = [{ bar: 2 }];
    
    const a3 = a1.concat(a2);
    const a4 = [...a1, ...a2];
    
    a3[0] === a1[0] // true
    a4[0] === a1[0] // true
    

      

    上面代码中,a3a4是用两种不同方法合并而成的新数组,但是它们的成员都是对原数组成员的引用,这就是浅拷贝。如果修改了原数组的成员,会同步反映到新数组。

    如果参数是一个真正的数组,Array.from会返回一个一模一样的新数组。

    Array.from([1, 2, 3])
    // [1, 2, 3]
    

    值得提醒的是,扩展运算符(...)也可以将某些数据结构转为数组。

    // arguments对象
    function foo() {
      const args = [...arguments];
    }

    基本用法

    Object.assign方法用于对象的合并,将源对象(source)的所有可枚举属性,复制到目标对象(target)。
    
    const target = { a: 1 };
    
    const source1 = { b: 2 };
    const source2 = { c: 3 };
    
    Object.assign(target, source1, source2);
    target // {a:1, b:2, c:3}
    Object.assign方法的第一个参数是目标对象,后面的参数都是源对象。
    
    注意,如果目标对象与源对象有同名属性,或多个源对象有同名属性,则后面的属性会覆盖前面的属性。
    
    const target = { a: 1, b: 1 };
    
    const source1 = { b: 2, c: 2 };
    const source2 = { c: 3 };
    
    Object.assign(target, source1, source2);
    target // {a:1, b:2, c:3}
    

      

    扩展运算符可以用于合并两个对象。
    
    let ab = { ...a, ...b };
    // 等同于
    let ab = Object.assign({}, a, b);
    如果用户自定义的属性,放在扩展运算符后面,则扩展运算符内部的同名属性会被覆盖掉。
    
    let aWithOverrides = { ...a, x: 1, y: 2 };
    // 等同于
    let aWithOverrides = { ...a, ...{ x: 1, y: 2 } };
    // 等同于
    let x = 1, y = 2, aWithOverrides = { ...a, x, y };
    // 等同于
    let aWithOverrides = Object.assign({}, a, { x: 1, y: 2 });
    上面代码中,a对象的x属性和y属性,拷贝到新对象后会被覆盖掉。
    
    这用来修改现有对象部分的属性就很方便了。
    
    let newVersion = {
      ...previousVersion,
      name: 'New Name' // Override the name property
    };
    

      

    // 去除数组的重复成员
    [...new Set(array)]
    

      

    这就提供了去除数组重复成员的另一种方法。
    
    function dedupe(array) {
      return Array.from(new Set(array));
    }
    
    dedupe([1, 1, 2, 3]) // [1, 2, 3]
    

      

     
  • 相关阅读:
    用一个测试类简化排序算法时间复杂度的研究
    用斗地主的实例学会使用java Collections工具类
    数据结构:用实例分析ArrayList与LinkedList的读写性能
    用一个通俗易懂的例子彻底说清楚单例模式
    用自定义链式栈解决力扣括号匹配问题
    数据结构之链式队列的代码实现及有趣应用
    用非常硬核的JAVA序列化手段实现对象流的持久化保存
    SpringBoot整合SpringSecurity实现JWT认证
    六百字搞懂lambda
    判空我推荐StringUtils.isBlank
  • 原文地址:https://www.cnblogs.com/guidan/p/9871711.html
Copyright © 2020-2023  润新知