ES6的對象擴展運算符(...
)可以用于復制對象、合并對象、傳遞函數參數等多種應用。
const obj1 = { name: 'Alice', age: 20 };
const obj2 = { ...obj1 };
console.log(obj2); // { name: 'Alice', age: 20 }
const obj1 = { name: 'Alice' };
const obj2 = { age: 20 };
const mergedObj = { ...obj1, ...obj2 };
console.log(mergedObj); // { name: 'Alice', age: 20 }
const userInfo = { name: 'Alice', age: 20 };
function printNameAndAge({ name, age }) {
console.log(`Name: ${name}, Age: ${age}`);
}
printNameAndAge(userInfo); // Name: Alice, Age: 20
const arr = [1, 2, 3];
function sum(a, b, c) {
return a + b + c;
}
console.log(sum(...arr)); // 6
const userInfo = { name: 'Alice', age: 20 };
const { name, age } = userInfo;
console.log(name, age); // Alice 20
需要注意的是,對象擴展運算符只能用于淺拷貝對象,如果對象中有嵌套對象,則只會拷貝對象的引用。