本文翻译自:How do I check if an object has a key in JavaScript? [duplicate]
This question already has an answer here: The problem here has the answer:
Which is the right thing to do? What is the right approach?
if (myObj['key'] == undefined)
or either
if (myObj['key'] == null)
or either
if (myObj['key'])
#1st Floor
Reference: https://stackoom.com/question/1uSA/ how to check whether an object has a key in JavaScript - repeat
#2nd Floor
Should use by You hasOwnProperty
. You should use hasOwnProperty
. For example: For example:
myObj.hasOwnProperty('myKey');
#3rd floor
At The the try JavaScript in operator . Try the JavaScript action .
if ('key' in myObj)
And the inverse. And inverse.
if (!('key' in myObj))
Be careful! Be careful! Of The in
operator Object The matches All Keys, Including Those in the prototype The Object apos catena alberghiera. in
Operator keys match all objects, including object key object prototype chain.
The Use myObj.hasOwnProperty('key')
to the Check Object AN's own Keys and return by Will only true
IF key
IS ON the Available myObj
Directly: Use myObj.hasOwnProperty('key')
to check the object's own key, and only myObj
directly available key
only to return true
:
myObj.hasOwnProperty('key')
A specific reason you have have The unless to use at The in
operator, a using myObj.hasOwnProperty('key')
Produces the Result at The code IS MOST looking for. Unless you have a specific reason to use in
operators, myObj.hasOwnProperty('key')
using myObj.hasOwnProperty('key')
will generate most of the code results are looking for.