如何检查对象是否在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'])

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值