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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3476255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:48:20  来源:igfitidea点击:

In Javascript. how can I tell if a field exists inside an object?

javascript

提问by Khoi

And of course I want to do this code-wise. It's not that there isn't alternative to this problem I'm facing, just curious.

当然,我想在代码方面做这个。并不是说我面临的这个问题没有替代方案,只是好奇。

采纳答案by Peter Kruithof

UPDATE: use the hasOwnPropertymethod as Gary Chambers suggests. The solution below will work, but it's considered best practice to use hasOwnProperty.

更新:使用hasOwnPropertyGary Chambers 建议的方法。下面的解决方案将起作用,但它被认为是使用hasOwnProperty.

if ('field' in obj) {
}

回答by Gary Chambers

This will ignore attributes passed down through the prototype chain.

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

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

回答by Eugene Ilyushin

In addition to the above, you can use following way:

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

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

回答by Aliaksandr Sushkevich

There is hasmethod in lodash library for this. It can even check for nested fields.

目前在lodash库此方法。它甚至可以检查嵌套字段。

_.has(object, 'a');     
_.has(object, 'a.b');

回答by will

After much frustration trying to test a field name which is passed via a variable, I came up with this:

在尝试测试通过变量传递的字段名称时非常沮丧,我想出了这个:

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

`

`

The function uses the try/catch function of javascript - if it can't set the field value it will trigger an error which is caught and passed back as false, otherwise true is returned.

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