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

来源:互联网 发布:网络攻防技术 课本 编辑:程序博客网 时间:2024/05/18 20:45

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

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

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

转载请保留此句:太阳火神的美丽人生 -  本博客专注于 敏捷开发及移动和物联设备研究:iOS、Android、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