prefer-object-spread

eslint报错:数组

  Use an object spread instead of `Object.assign` eg: `{ ...foo }`.(prefer-object-spreadspa

即:eslint

  禁止使用以对象字面量做为第一个参数的 Object.assign,优先使用对象扩展。
code

 

 

示例:(注意:对象字面量)对象

Object.assign({}, foo)

改成:

{ ...foo }



思考一下:
Object.assign经常使用来浅拷贝,那扩展符赋值的对象是从新开辟的堆内存仍是指向的扩展对象的堆内存?

    const a = { a: 'a' };
    const b = { ...a };
    console.log('b=', b);  // b= {a: "a"}
    a.a = 'c';
    console.log('b变了吗', b); // b变了吗 {a: "a"}   

  

  答案很明显,我想浅拷贝一个a, 扩展运算符和Object.assign都能浅拷贝对象blog

 

  那数组会怎样?内存

  

    const a = ['a', 'b'];
    const b = [...a];
    console.log('b=', b);  // b= ["a", "b"]
    a[1] = 'c';
    console.log('b变了吗', b); // b变了吗 ["a", "b"]

 

  很好,数组也能放心的浅拷贝;string

  

  等等。。。console

  

  若是是数组对象呢?class

 

    const a = [{ a: 'a' }];
    const b = [...a];
    console.log('b=', JSON.stringify(b));  // b= [{"a":"a"}]
    a[0].a = 'c';
    console.log('b变了吗', JSON.stringify(b)); // b变了吗 [{"a":"c"}]

 

  变了,结果说明展开符只对数组里面的对象进行了展开,对象里面的属性仍是指向的原来的内存地址,因此深拷贝行不通,目前来看和Object.assign的浅拷贝做用同样。

 

那...等等,

  

  Object.assign还有合并的做用,再来试试扩展符合并。

  

  

    const a = { a1: 'a1', a2: 'a2' };
    const b = { b1: 'b1', a2: 'b2' };
    const c = Object.assign({}, a, b);
    const d = { ...a, ...b };
    const e = { ...b, ...a };
    console.log('c', c);  // c {a1: "a1", a2: "b2", b1: "b1"}
    console.log('d', d);  // d {a1: "a1", a2: "b2", b1: "b1"}
    console.log('e', e);  // e {b1: "b1", a2: "a2", a1: "a1"}

 

   结果同样,Object.assign将b和a的属性合并到空对象里,相同属性会覆盖合并取后面的值,扩展符直接合并两个对象的属性,合并关系都是后面的覆盖前面的值

 

   那么,合并数组呢?

 

    const a = ['a', 'b'];
    const b = ['a', 'c'];
    const c = Object.assign([], a, b);
    const d = [...a, ...b];
    console.log('c', c);  // c ["a", "c"]
    console.log('d', d);  // d ["a", "b", "a", "c"]

 

   发生了什么?

   Object.assign处理数组时,会把数组视为对象,而后按顺序覆盖前面的值,因此b中的'a'覆盖了a中的'a', b中的'c'覆盖了a中的'b',而扩展符和concat方法同样合并数组

 

   合并数组时,Object.assign和扩展符做用不同了。

   

   那么,复杂数组呢?

    const a = [{ x: 'x', y: 'y' }];
    const b = [{ z: 'z', y: 'm' }];
    const c = Object.assign([], a, b);
    const d = [...a, ...b];
    console.log('c', JSON.stringify(c)); // c [{"z":"z","y":"m"}]
    console.log('d', JSON.stringify(d)); // d [{"x":"x","y":"y"},{"z":"z","y":"m"}]
    b[0].z = 'n';
    console.log('c', JSON.stringify(c)); // c [{"z":"n","y":"m"}]
    console.log('d', JSON.stringify(d)); // d [{"x":"x","y":"y"},{"z":"n","y":"m"}]

  

  Object.assign毫无悬念的后面的覆盖前面了(将数组看作对象时,属性就是下标),引用类型指向的仍是原来的内存地址

  

 

最后:

  

  虽说Object.assign和...扩展符不少时候能混用,但对数组进行操做的时候必定要当心二者的区别,否则合并覆盖变成合并拼接,因此请牢记使用以对象字面量做为第一个参数的 Object.assign,优先使用对象扩展

本站公众号
   欢迎关注本站公众号,获取更多信息