[英]JS: weird object comparison behavior
給出以下代碼:
const name = { name: 'amy' }; function greet(person) { if (person == { name: 'amy' }) { return 'hey amy'; } else { return 'hey there'; } } console.log( greet(name) // 'hey amy' ); console.log( greet({ name:'amy' }) // 'hey there' ); console.log(name == { name: 'amy' }); // true console.log(name === { name: 'amy' }); // false console.log(Object.is(name, { name: 'amy' })); // false
為什么在使用name
變量而不是對象文字時雙精度比較返回true
?
首先,我認為可能是因為對象具有相同的內存地址,但是正如人們看到的那樣,這是不正確的。
而且,如果我們顛倒過來並在函數內部定義變量,則比較返回false
! (代碼中未顯示,但您可以簽出)
我很困惑,不勝感激。
編輯: 這是我測試過代碼的地方。 Chrome中的Nodejs和瀏覽器控制台為我提供了常規結果,應該是這樣。 所以也許是關於口譯員的事。
您假定您在腦海中就想着Javascript將使用==
進行比較,但事實並非如此。 但是由於這是一個自定義對象,所以您不能指望Javascript會為您提供自定義實現。 您應該自己實現它。
唯一可行的情況是,使用===
運算符檢查對象是否相同,但按其內存地址進行檢查,從而跳過任何custom-object-data-based
比較。
這里的問題是為變量使用單詞name
。
在瀏覽器中, window
對象具有name
屬性,該屬性必須始終為字符串。 如果您嘗試為其分配非字符串的內容,它將被轉換為一個。
然后,當您將一個對象與一個字符串進行比較時,該對象也將被轉換並比較兩個字符串。 這就是為什么您看到它有時返回true的原因。 例:
// This will end up being assigned to window.name, and will be converted to a string. var name = {name: "amy"} console.log(name) // [object Object] // Then, when you compare that to another object using ==, the object will also be converted to string. console.log(name == {name: "amy"}) // true, because the string [object Object] is equal to itself.
將變量的名稱更改為其他名稱,或者使用let
或const
,問題應消失:
// This will end up being assigned to window.other, but isn't converted to string var other = {name: "amy"} console.log(other) // {"name": "amy"} // Now, both are objects, and unless they are the exact same object, comparing two objects is always false. console.log(other == {name: "amy"}) // false, no two distinct objects are ever equal
// Using let will not assign this variable to window. let name = {name: "amy"} console.log(name) // {"name": "amy"} // Again, now we compare two distict objects, which always results in false. console.log(name == {name: "amy"}) // false
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.