我正在将 objA 复制到 objB
const objA = { prop: 1 },
const objB = objA;
objB.prop = 2;
console.log(objA.prop); // logs 2 instead of 1
数组也有同样的问题
const arrA = [1, 2, 3], const arrB = arrA; arrB.push(4); console.log(arrA.length); // `arrA` has 4 elements instead of 3.
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
总而言之,为了澄清起见,有四种复制 JS 对象的方法。
const a = { x: 0} const b = a; b.x = 1; // also updates a.x...{}或Object.assign()。const a = { x: 0, y: { z: 0 } }; const b = {...a}; // or const b = Object.assign({}, a); b.x = 1; // doesn't update a.x b.y.z = 1; // also updates a.y.zconst a = { x: 0, y: { z: 0 } }; const b = JSON.parse(JSON.stringify(a)); b.y.z = 1; // doesn't update a.y.zlodash这样的实用程序库。import { cloneDeep } from "lodash"; const a = { x: 0, y: { z: (a, b) => a + b } }; const b = cloneDeep(a); console.log(b.y.z(1, 2)); // returns 3Object.create()确实创建了一个新对象。这些属性在对象之间共享(更改其中一个也会更改另一个)。与普通副本的区别在于,属性被添加到新对象的原型__proto__下。当您从不更改原始对象时,这也可以用作浅拷贝,但我建议使用上述方法之一,除非您特别需要这种行为。