ES6合并對象的方法有以下幾種:
使用對象展開運算符(…):
const obj1 = {a: 1, b: 2};
const obj2 = {c: 3, d: 4};
const merged = {...obj1, ...obj2};
console.log(merged); // {a: 1, b: 2, c: 3, d: 4}
使用Object.assign()方法:
const obj1 = {a: 1, b: 2};
const obj2 = {c: 3, d: 4};
const merged = Object.assign({}, obj1, obj2);
console.log(merged); // {a: 1, b: 2, c: 3, d: 4}
使用Object.getOwnPropertyDescriptors()方法和Object.defineProperties()方法:
const obj1 = {a: 1, b: 2};
const obj2 = {c: 3, d: 4};
const descriptors = Object.getOwnPropertyDescriptors(obj2);
const merged = Object.defineProperties(obj1, descriptors);
console.log(merged); // {a: 1, b: 2, c: 3, d: 4}
這些方法都可以用來合并多個對象的屬性,并創(chuàng)建一個新的對象。