Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
336 views
in Technique[技术] by (71.8m points)

javascript - 如何检查对象是否在JavaScript中有密钥? [重复](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'])
  ask by translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...