本文翻譯自:How do I check if an object has a key in JavaScript? [duplicate]
This question already has an answer here: 這個問題在這裏已有答案:
Which is the right thing to do? 哪個是正確的做法?
if (myObj['key'] == undefined)
or 要麼
if (myObj['key'] == null)
or 要麼
if (myObj['key'])
#1樓
參考:https://stackoom.com/question/1uSA/如何檢查對象是否在JavaScript中有密鑰-重複
#2樓
You should use hasOwnProperty
. 你應該使用hasOwnProperty
。 For example: 例如:
myObj.hasOwnProperty('myKey');
#3樓
Try the JavaScript in operator . 嘗試的 JavaScript操作 。
if ('key' in myObj)
And the inverse. 和逆。
if (!('key' in myObj))
Be careful! 小心! The in
operator matches all object keys, including those in the object's prototype chain. in
運算符匹配所有對象鍵,包括對象原型鏈中的對象鍵。
Use myObj.hasOwnProperty('key')
to check an object's own keys and will only return true
if key
is available on myObj
directly: 使用myObj.hasOwnProperty('key')
檢查對象自己的密鑰,只有在myObj
直接可用key
時才返回true
:
myObj.hasOwnProperty('key')
Unless you have a specific reason to use the in
operator, using myObj.hasOwnProperty('key')
produces the result most code is looking for. 除非您有特定的理由使用in
運算符, myObj.hasOwnProperty('key')
使用myObj.hasOwnProperty('key')
會生成大多數代碼正在查找的結果。