How to check whether the object has a key in JavaScript? [repeat]

本文翻译自: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 inoperator Object The matches All Keys, Including Those in the prototype The Object apos catena alberghiera. inOperator 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 trueIF keyIS ON the Available myObjDirectly: Use myObj.hasOwnProperty('key')to check the object's own key, and only myObjdirectly available keyonly to return true:

myObj.hasOwnProperty('key')

A specific reason you have have The unless to use at The inoperator, a using myObj.hasOwnProperty('key')Produces the Result at The code IS MOST looking for. Unless you have a specific reason to use inoperators, myObj.hasOwnProperty('key')using myObj.hasOwnProperty('key')will generate most of the code results are looking for.

Original articles published 0 · won praise 73 · views 550 000 +

Guess you like

Origin blog.csdn.net/w36680130/article/details/105312160