vue合并对象Object.assign()

一、定义

Object.assign() 方法用于将所有可枚举属性的值从一个或多个源对象复制到目标对象。它将返回目标对象。【简单来说就是合并对象(且是浅拷贝)】

二、用法

Object.assign(target, ...sources)

target:目标对象

source:源对象(一个或多个)

三、使用情景

// 一般的使用
const target = { a: 1, b: 2 };
const source = { c: 3 };
Object.assign(target, source);
console.log("console log1:", target);

// 如果目标和源有相同属性,目标会被源覆盖
const target = { a: 1, b: 2};
const source = { b: 3, d: 4}; // 覆盖target的b
Object.assign(target, source);
console.log("console log2:", target);

// 如果多个源有相同属性,目标会被最后一个源覆盖
const target = { a: 1, b: 2};
const source1 = { b: 3, d: 4}; // 覆盖target的b
const source2 = { b: 4};       // 覆盖source2的b
Object.assign(target, source1, source2);
console.log("console log3:", target);
source1.b = 5
console.log('source1:',source1);
console.log('target:', target);

const target = { a:'1', b: '2'};
const source1 = { };
const source2 = { b: '' };
Object.assign(target, source1, source2);
console.log("console log4:", target);
source1.b = 5
console.log('source1:',source1);
console.log('target:', target);
console log1: { a: 1, b: 2, c: 3 }

console log2: { a: 1, b: 3, d: 4 }

console log3: { a: 1, b: 4, d: 4 }
source1: { b: 5, d: 4 }
target: { a: 1, b: 4, d: 4 }

console log4: { a: '1', b: ''}
source1: { b: 5 }
target: { a: '1', b: '' }

四、深拷贝与浅拷贝

// 一般的修改源的值
const target = { a: 1 };
const source = { a: 2, b: 3 };
Object.assign(target, source);
console.log('target:', target);
console.log('source:', source);
source.a = 4;
console.log('修改后target:', target);
console.log('修改后source:', source);

// 浅拷贝
const target = { a: 1 };
const source = { a: 2, b: { c: 4 }};
Object.assign(target, source);
console.log('target:', target);
console.log('source:', source);
source.b.c = 10;
console.log('修改后target:', target);    // 目标受源的影响
console.log('修改后source:', source);

// 深拷贝
const target = { a: 1 };
const source = { a: 2, b: { c: 4 }};
Object.assign(target, JSON.parse(JSON.stringify(source)));
console.log('target:', target);
console.log('source:', source);
source.b.c = 10;
console.log('修改后target:', target);    // 目标不受源的影响
console.log('修改后source:', source);
target: { a: 2, b: 3 }
source: { a: 2, b: 3 }
修改后target: { a: 2, b: 3 }
修改后source: { a: 4, b: 3 }

// 浅拷贝
target: { a: 2, b: { c: 4 }}
source: { a: 2, b: { c: 4 }}
修改后target: { a: 2, b: { c: 10 }}    // 目标受源的影响
修改后source: { a: 4, b: { c: 10 }}

// 深拷贝
target: { a: 2, b: { c: 4 }}
source: { a: 2, b: { c: 4 }}
修改后target: { a: 2, b: { c: 4 }}    // 目标不受源的影响
修改后source: { a: 4, b: { c: 10 }}

五、其他

继承属性和不可枚举属性不能拷贝。

异常会终止拷贝。

原始类型会被包装,null 和 undefined 会被忽略。

参考资料和更多示例:Object.assign() - JavaScript | MDN (mozilla.org)

猜你喜欢

转载自blog.csdn.net/weixin_43961652/article/details/129200297