在 JavaScript 中,深度克隆物件的最高效方法是什麼?
在 JavaScript 中,物件是鍵值對的集合。物件的屬性是鍵,並用字串表示。鍵的值是給定物件屬性的值。在 JavaScript 中,物件可以透過多種方式複製到其他物件,其中一些將在下面討論。
使用擴充套件運算子(…),
使用 assign() 函式和
使用 JSON.parse() 和 JSON.stringify() 函式。
使用 Json.parse() 和 Stingify() 方法
在上面提到的三種方法中,為了深度克隆物件,使用 JSON.stringify() 和 JSON.parse() 函式。
parse() 方法接受一個 JSON 字串作為引數,並根據該字串建立一個 JavaScript 物件。
stringify() 方法將 JavaScript 物件的值轉換為 JSON 字串。
使用這兩種方法,您可以快速輕鬆地將原始物件複製到新物件中。當給定輸入為數字、字串和物件字面量時,可以使用 parse 進行復制。parse() 函式會將字串解析為 JavaScript 物件,透過這種方式,這兩個物件將擁有各自的記憶體。
語法
下面給出 parse 函式的語法。
JSON.parse(JSON.stringify(originalObjectName))
示例 1
這是 parse() 方法和 stringify() 複製物件的示例 -
let employee = { emp_name: 'Abdul Rawoof', company: 'Tutorials Point', emp_id: 'TP10000', role: 'Software Engineer-Intern', salary: 18000 } let cpyEmployee = JSON.parse(JSON.stringify(employee)) console.log("This is the original object:",employee) console.log("This is the new copied object:",cpyEmployee) cpyEmployee.emp_name = 'B Jason' cpyEmployee.emp_id = 'TP9999' cpyEmployee.role = 'Content Writing-Intern' console.log("The copied object with updations is:",cpyEmployee)
示例 2
以下是使用 parse() 和 stringify() 方法克隆物件的另一個示例 -
let obj = { foo: 1, bar: { baz: 'test' } } let newObj = JSON.parse(JSON.stringify(obj)); obj.bar.baz = 20; console.log(obj); console.log(newObj);
Object.assign() 方法
OBJECT.assign() 函式用於將原始物件複製到新物件中。它與擴充套件運算子的區別在於,當存在巢狀物件時,如果使用 assign() 複製物件,則巢狀物件不會更改,而物件的其它變數可以更改。
示例
此示例演示瞭如何在 JavaScript 中使用 assign() 合併物件。
var empDetails = { emp_name: "Abdul Rawoof", emp_sex: "M", emp_age: 23 } var empCompany = { emp_id: "TP1000", emp_role: "Software Engineer-Intern", emp_salary: 18000 } console.log("The employee details object is:", empDetails) console.log("The employee company object is:",empCompany) var mergeObj = Object.assign({},empDetails,empCompany) console.log("The merged object is",mergeObj)
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP