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)中引入的。
spread 语法可用于制作对象的浅拷贝。这意味着它将复制对象。但是,引用了更深层次的对象。例如,
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时,
math对象的值
person 对象的 code> 键也会改变。
示例 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 对象字面量。它不适用于具有函数或符号属性的对象文字。

