JavaScript 对象是一种复杂数据类型,它可以包含各种数据类型。例如,
const person = {
name: 'John',
age: 21,
}
这里,person
是一个对象。现在,你不能通过像这样的方式克隆一个对象。
const copy = person;
console.log(copy); // {name: "John", age: 21}
在上面的程序中,copy
变量的值与 person
对象相同。但是,如果你更改 copy
对象的值,person
对象的值也会更改。例如,
copy.name = 'Peter';
console.log(copy.name); // Peter
console.log(person.name); // Peter
两个对象都显示了更改,因为对象是引用类型。copy
和 person
都指向同一个对象。
示例 1. 使用 Object.assign() 克隆对象
// program to clone the object
// declaring object
const person = {
name: 'John',
age: 21,
}
// cloning the object
const clonePerson = Object.assign({}, person);
console.log(clonePerson);
// changing the value of clonePerson
clonePerson.name = 'Peter';
console.log(clonePerson.name);
console.log(person.name);
输出
{name: "John", age: 21} Peter John
Object.assign()
方法是ES6标准的一部分。Object.assign()
方法执行深拷贝,并从一个或多个对象复制所有属性。
注意:作为第一个参数的空 {}
确保您不会更改原始对象。
示例 2:使用展开语法克隆对象
// program to clone the object
// declaring object
const person = {
name: 'John',
age: 21,
}
// cloning the object
const clonePerson = { ... person}
console.log(clonePerson);
// changing the value of clonePerson
clonePerson.name = 'Peter';
console.log(clonePerson.name);
console.log(person.name);
输出
{name: "John", age: 21} Peter John
展开语法 ...
在后续版本 (ES6) 中引入。
展开语法可用于创建对象的浅拷贝。这意味着它会复制对象。但是,更深层的对象会被引用。例如,
const person = {
name: 'John',
age: 21,
// the inner objects will change in the shallow copy
marks: { math: 66, english: 73}
}
// cloning the object
const clonePerson = { ... person}
console.log(clonePerson); // {name: "John", age: 21, marks: {…}}
// changing the value of clonePerson
clonePerson.marks.math = 100;
console.log(clonePerson.marks.math); // 100
console.log(person.marks.math); // 100
在这里,当 clonePerson
对象的内部对象值 math
更改为 100 时,person
对象中 math
键的值也会更改。
示例 3:使用 JSON.parse() 克隆对象
// program to clone the object
// declaring object
const person = {
name: 'John',
age: 21,
}
// cloning the object
const clonePerson = JSON.parse(JSON.stringify(person));
console.log(clonePerson);
// changing the value of clonePerson
clonePerson.name = 'Peter';
console.log(clonePerson.name);
console.log(person.name);
输出
{name: "John", age: 21} Peter John
在上面的程序中,JSON.parse()
方法用于克隆对象。
注意:JSON.parse()
仅适用于 Number
和 String
对象字面量。它不适用于具有 function
或 symbol
属性的对象字面量。
另请阅读