首頁 > web前端 > js教程 > 主體

JavaScript 中物件的淺拷貝與深拷貝

Mary-Kate Olsen
發布: 2024-10-04 22:25:02
原創
484 人瀏覽過

Shallow vs Deep Copy of Objects in JavaScript

When we need to copy an object to another object, we generally use something like this:


const mainObject = { id: 1 };
const secondaryObject = { ...mainObject };


登入後複製

But this only works for copying the shallow properties of the object. If we have a case like the following code, the scenario changes:


const mainObject = { id: 1, user: { name: 'John Doe', age: 30 } };
const secondaryObject = { ...mainObject };


登入後複製

The property user won't be copied; it will still be related to mainObject. So, if we alter the user property, it will also affect mainObject. To solve this, we can do the following:


const mainObject = { id: 1, user: { name: 'John Doe', age: 30 } };
const deepCopy = JSON.parse(JSON.stringify(mainObject ));


登入後複製

Now, we have a deep copy of mainObject, with two distinct memory addresses.

以上是JavaScript 中物件的淺拷貝與深拷貝的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板