Object.assgin()

57 阅读1分钟

1.Object.assgin 的用法

该方法作用于可枚举属性,对于不可枚举对象不进行拷贝,方法本义是将一个或者多个源对象拷贝至目标对象:

    const target = { a: 1, b: 2 };   
    const source = { b: 4, c: 5 };   
    const returnedTarget = Object.assign(target, source); 
    console.log(target);
    // Expected output: Object { a: 1, b: 4, c: 5 }

该方法拷贝是对对象进行浅拷贝,即拷贝对象的引用。

    console.log(returnedTarget === target);
    // Expected output: true

同时可以拷贝多个源对象至目标对象,如果属性重复,那么后面的会覆盖前面的。

需要注意的是:该拷贝一般至作用于对象,对于字符串,会先把它转化成字符数组,然后进行处理:

const v1 = "abc";
const v2 = true;
const v3 = 10;
const v4 = Symbol("foo");

const obj = Object.assign({}, v1, null, v2, undefined, v3, v4);
// Primitives will be wrapped, null and undefined will be ignored.
// Note, only string wrappers can have own enumerable properties.
console.log(obj); // { "0": "a", "1": "b", "2": "c" }

对于数字或者boolean类型的值,会直接忽略,从上面的示例也可以看出,对于数组使用该方法,那么最后是将数组转化为对象,然后里面的值即为value,下表及为键:

const returnedTarget = Object.assign({},[1,2,3]);
console.log(returnedTarget);
//Expected output: Object { 0: 1, 1: 2, 2: 3 }
const returnedTarget = Object.assign([1,2,3],[4,5]);
console.log(returnedTarget);
//Array [4, 5, 3]
//直接进行覆盖



const returnedTarget = Object.assign([4,5],[1,2,3]);
console.log(returnedTarget);
// Array [1, 2, 3]
//直接进行覆盖

从上面的示例也可以看出,对于数组,先是转对象,然后进行覆盖。