检查JavaScript对象中是否存在密钥?如何检查JavaScript对象或数组中是否存在特定的键?如果一个密钥不存在,并且我试图访问它,它会返回false吗?还是犯了个错误
3 回答
猛跑小猪
TA贡献1858条经验 获得超8个赞
undefined
?
var obj = { key: undefined };obj["key"] != undefined // false, but the key exists!
in
"key" in obj // true, regardless of the actual value
!("key" in obj) // true if "key" doesn't exist in object!"key" in obj // ERROR! Equivalent to "false in obj"
hasOwnProperty
:
obj.hasOwnProperty("key") // true
in
, hasOwnProperty
undefined
慕桂英4014372
TA贡献1871条经验 获得超13个赞
它会回来的undefined.
var aa = {hello: "world"};
alert( aa["hello"] ); // popup box with "world"
alert( aa["goodbye"] ); // popup box with "undefined"
undefined
// note the three equal signs so that null won't be equal to undefinedif( aa["goodbye"] === undefined ) { // do something}
undefined
in
// this works even if you have {"goodbye": undefined}if( "goodbye" in aa ) { // do something}
添加回答
举报
0/150
提交
取消