本文翻译自: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')
会生成大多数代码正在查找的结果。