下面的代碼,我想要列印出hey jack,結果卻列印出hey rose,為什么?
1 function greet(person) { 2 if (person == {name: 'jack'}) { 3 console.log('hey jack') 4 return 5 } else { 6 console.log('hey rose') 7 return 8 } 9 } 10 greet({name: 'jack'})
這里問題出在{ name: 'jack' } != { name: 'jack' },物件是復雜資料型別,復雜資料型別的值存盤在堆記憶體,堆疊記憶體儲的是復雜資料型別的地址(地址指向真實資料),當比較兩個物件時,JavaScript都會比較物件在記憶體中的參考地址,這個例子中,兩個物件雖然都有相同的屬性和值,但它們在記憶體中地址是不同的,所以是兩個不同的物件,
正確的解決方法應該是比較物件屬性的值:
1 function greet(person) { 2 if (person.name === 'jack') { 3 console.log('jack'); 4 return 5 } else { 6 console.log('rose'); 7 return 8 } 9 } 10 greet({ 11 name: 'jack' 12 })
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/177557.html
標籤:JavaScript
上一篇:js 一些有意思的小Demo
