JavaScript中的對象比較[重複] - Object comparison in JavaScript [duplicate]

問題:

This question already has answers here : 這個問題已經在這裏有了答案
Closed 3 years ago . 3年前關閉。

What is the best way to compare objects in JavaScript? 在JavaScript中比較對象的最佳方法是什麼? spa

Example: 例: .net

var user1 = {name : "nerd", org: "dev"};
var user2 = {name : "nerd", org: "dev"};
var eq = user1 == user2;
alert(eq); // gives false

I know that two objects are equal if they refer to the exact same object , but is there a way to check if they have the same attributes' values? 我知道兩個對象若是引用徹底相同的對象則相等 ,可是有沒有辦法檢查它們是否具備相同的屬性值? code

The following way works for me, but is it the only possibility? 如下方法對我有用,但這是惟一的可能性嗎? 對象

var eq = Object.toJSON(user1) == Object.toJSON(user2);
alert(eq); // gives true

解決方案:

參考一: https://stackoom.com/question/4U3G/JavaScript中的對象比較-重複
參考二: https://oldbug.net/q/4U3G/Object-comparison-in-JavaScript-duplicate
相關文章
相關標籤/搜索