P粉3948122772023-08-28 17:35:35
總而言之,為了澄清起見,有四種複製 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.z
const a = { x: 0, y: { z: 0 } }; const b = JSON.parse(JSON.stringify(a)); b.y.z = 1; // doesn't update a.y.z
lodash
這樣的實用程式庫。 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 3
Object.create()
確實建立了一個新物件。這些屬性在物件之間共用(更改其中一個也會更改另一個)。與普通副本的區別在於,屬性被加入到新物件的原型 __proto__
下。當您從不更改原始物件時,這也可以用作淺拷貝,但我建議使用上述方法之一,除非您特別需要這種行為。 P粉5205457532023-08-28 12:57:02
很明顯,您對語句 var tempMyObj = myObj;
的作用有些誤解。
在 JavaScript 中,物件是透過引用(更準確地說是引用的值)傳遞和分配的,因此 tempMyObj
和 myObj
都是對相同物件的參考。
這是一個簡化的插圖,可以幫助您直觀地了解正在發生的事情
// [Object1]<--------- myObj var tempMyObj = myObj; // [Object1]<--------- myObj // ^ // | // ----------- tempMyObj
正如您在賦值後所看到的,兩個引用都指向同一個物件。
如果您需要修改其中一個而不是另一個,則需要建立副本。
// [Object1]<--------- myObj const tempMyObj = Object.assign({}, myObj); // [Object1]<--------- myObj // [Object2]<--------- tempMyObj
舊答案:
#這裡有幾種建立物件副本的其他方法
由於您已經在使用 jQuery:
var newObject = jQuery.extend(true, {}, myObj);
使用普通 JavaScript
function clone(obj) { if (null == obj || "object" != typeof obj) return obj; var copy = obj.constructor(); for (var attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr]; } return copy; } var newObject = clone(myObj);#