This question already has an answer here:
这个问题已经有了答案:
- How do I check if an object has a property in JavaScript? 23 answers
- 如何检查对象在JavaScript中是否具有属性?23日答案
Which is the right thing to do?
哪一种做法是正确的?
if (myObj['key'] == undefined)
or
或
if (myObj['key'] == null)
or
或
if (myObj['key'])
2 个解决方案
#1
1162
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:
使用myobject . hasownproperty ('key')检查对象自己的键,只有在myObj上有键时才返回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操作符,否则使用myobject . hasownproperty(“key”)将生成大多数代码所需要的结果。
#2
319
You should use hasOwnProperty
. For example:
您应该使用hasOwnProperty。例如:
myObj.hasOwnProperty('myKey');
#1
1162
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:
使用myobject . hasownproperty ('key')检查对象自己的键,只有在myObj上有键时才返回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操作符,否则使用myobject . hasownproperty(“key”)将生成大多数代码所需要的结果。
#2
319
You should use hasOwnProperty
. For example:
您应该使用hasOwnProperty。例如:
myObj.hasOwnProperty('myKey');