JavaScript 检查一个 JSON 对象中是否对存指这下的 Key

JavaScript 检查一个 JSON 对象中是否对存指定的 Key

太阳火神的美丽人生 (http://blog.csdn.net/opengl_es)

本文遵循“署名-非商业用途-保持一致”创作公用协议

转载请保留此句:太阳火神的美丽人生 -  本博客专注于 敏捷开发及移动和物联设备研究:iOSAndroid、Html5、Arduino、pcDuino否则,出自本博客的文章拒绝转载或再转载,谢谢合作。


Actually, checking for undefined-ness is not an accurate way of testing whether a key exists. 

What if the key exists but the value is actually undefined? 

实际上,测试未定义这种结果确实不是一个比较精确的检测键是否存在的有效方法。

var obj = { key: undefined }; 
obj["key"] != undefined

false, but the key exists! 

上面的结果是 false ,但这个键确是存在的。


You should instead use the in operator: 
你应该换用 in 操作:

"key" in obj 

true, regardless of the actual value 

结果是 true,不考虑实际值

If you want to check if a key doesn't exist, remember to use parenthesis: 
如果你想要检查一个键是否不存在,记得使用取反:
!("key" in obj) 

true if "key" doesn't exist in object 

如果键存在于这个对象里,那么结果是 true

!"key" in obj
ERROR! Equivalent to "false in obj" 

这个有错!等于 "false in obj" 


Or, if you want to particularly test for properties of the object instance (and not inherited properties), use hasOwnProperty: 

或者,如jusi你特别想检测一下对象实际的属性(并非继承的属性),那么使用 hasOwnProperty:

obj.hasOwnProperty("key") 

true

这个测试的结果是 true



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值