在Javascript中。如何判断对象内部是否存在字段?


76

当然,我想在代码方面做到这一点。这并不是我面临的这个问题没有别的选择,只是好奇。

Answers:


77

更新:使用hasOwnProperty加里·钱伯斯(Gary Chambers)建议的方法。以下解决方案可以使用,但被认为是使用的最佳实践hasOwnProperty

if ('field' in obj) {
}

1
需要注意的是完全一样的方式,你可以检查密钥是否存在关联数组(这是因为通常对象在事实上关联数组)
安德烈Zilio

一些短毛猫会抱怨这种语法。按照@GaryChambers的建议使用hasOwnProperty更安全
Jayd 2014年

同意,我更新了答案,将其他人指向正确的方向。
Peter Kruithof 2014年

@Jayd与hasOwnProperty相比,此语法有什么缺点?
Jo Smo 2015年

2
@JoSmo in语法可以为原型链中的属性返回true,正如Gary Chambers在回答中提到的那样。具有自己的属性将仅检查当前对象特有的字段。
杰德

117

这将忽略通过原型链向下传递的属性。

if(obj.hasOwnProperty('field'))
{
    // Do something
}

2

除上述之外,您还可以使用以下方式:

if(obj.myProperty !== undefined) {
}

5
此方法无法区分缺失字段和具有未定义值的现有字段。例如:{}{a : undefined}
Arashsoft

1

在尝试测试通过变量传递的字段名称后,经过很多挫败之后,我想到了:

`function isset(fName){ 
    try{
        document.getElementById(fName).value=document.getElementById(fName).value;  
        return true;
    }catch(err){
        return false;
    }
 }

`

该函数使用javascript的try / catch函数-如果无法设置字段值,则会触发错误,该错误将被捕获并传回false,否则返回true。


By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.