在 JavaScript 中使用对象时,理解 对象引用 和 对象复制 之间的区别至关重要。以下是详细概述:
let obj1 = { name: "Alice" }; let obj2 = obj1; // obj2 now references the same object as obj1 obj2.name = "Bob"; console.log(obj1.name); // Output: "Bob"
let a = { key: "value" }; let b = { key: "value" }; console.log(a === b); // Output: false (different references) let c = a; console.log(a === c); // Output: true (same reference)
对象复制主要有两种类型:浅复制和深复制。
浅复制技术:
Object.assign():
let original = { name: "Alice", details: { age: 25 } }; let copy = Object.assign({}, original); copy.details.age = 30; console.log(original.details.age); // Output: 30 (shared reference)
扩展运算符 (...):
let original = { name: "Alice", details: { age: 25 } }; let copy = { ...original }; copy.details.age = 30; console.log(original.details.age); // Output: 30 (shared reference)
这两种方法都会创建浅表副本,这意味着嵌套对象仍然是链接的。
深度复制技术:
JSON.parse() 和 JSON.stringify():
let original = { name: "Alice", details: { age: 25 } }; let copy = JSON.parse(JSON.stringify(original)); copy.details.age = 30; console.log(original.details.age); // Output: 25
StructuredClone()(现代 JavaScript):
let original = { name: "Alice", details: { age: 25 } }; let copy = structuredClone(original); copy.details.age = 30; console.log(original.details.age); // Output: 25
自定义库:
let obj1 = { name: "Alice" }; let obj2 = obj1; // obj2 now references the same object as obj1 obj2.name = "Bob"; console.log(obj1.name); // Output: "Bob"
Action | Result |
---|---|
Assignment (=) | Creates a reference. Changes to one variable affect the other. |
Shallow Copy | Creates a new object but retains references for nested objects. |
Deep Copy | Creates a completely independent object, including nested structures. |
结果
以上是了解 JavaScript 对象引用和复制 - 简要说明的详细内容。更多信息请关注PHP中文网其他相关文章!