「這個 key 到底有沒有送過來?」是前端防禦式程式設計的必答題。網路上流傳的寫法有些其實是錯的,以下逐一檢視。
obj["key"] != undefined
這個判斷有漏洞。如果後端確實送了 key,但值本身就是 undefined,那麼這句會回傳 false,讓你誤以為欄位不存在。
!("key" in obj)
obj.hasOwnProperty("key")
原文說得很清楚:
Actually, checking for undefined-ness is not an accurate way of testing whether a key exists. What if the key exists but the value is actually undefined?
var obj = { key: undefined }; obj["key"] != undefined // false, but the key exists!You should instead use the in operator:
"key" in obj // true, regardless of the actual valueIf you want to check if a key doesn't exist, remember to use parenthesis:
!("key" in obj) // true if "key" doesn't exist in object !"key" in obj // ERROR! Equivalent to "false in obj"Or, if you want to check if a key doesn't exist for the object instance (and not inherited properties), use hasOwnProperty:
obj.hasOwnProperty("key") // true
in 會連原型鏈上的屬性一起算進去,hasOwnProperty 只看自身屬性。判斷「後端有沒有送這個欄位」時,你要的是後者,因為前者會把 toString、constructor 這類繼承成員也算成存在——用 'toString' in obj 測試就會回傳 true,這通常不是你想知道的。
更穩健的寫法是借用原型方法,避免 obj 自己被覆寫:
Object.prototype.hasOwnProperty.call(obj, 'key')
若環境支援,也可使用更明確的 ES2022 語法:
Object.hasOwn(obj, 'key')
至於「欄位存在但值為 undefined」這種需要區分的場景,可以搭配 'key' in obj 判斷存在性,再用 obj.key === undefined 判斷值——兩件事分開處理,語意才不會糊在一起。