如何使用保存属性名称的变量检查对象属性是否存在? [英] How to check if object property exists with a variable holding the property name?
本文介绍了如何使用保存属性名称的变量检查对象属性是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在检查对象属性是否存在,其中的变量包含相关属性名称.
I am checking for the existence of an object property with a variable holding the property name in question.
var myObj;
myObj.prop = "exists";
var myProp = "p"+"r"+"o"+"p";
if(myObj.myProp){
alert("yes, i have that property");
};
这是 undefined
因为它正在寻找 myObj.myProp
但我希望它检查 myObj.prop
This is undefined
because it's looking for myObj.myProp
but I want it to check for myObj.prop
推荐答案
var myProp = 'prop';
if(myObj.hasOwnProperty(myProp)){
alert("yes, i have that property");
}
或
var myProp = 'prop';
if(myProp in myObj){
alert("yes, i have that property");
}
或
if('prop' in myObj){
alert("yes, i have that property");
}
请注意,hasOwnProperty
不会检查继承的属性,而 in
会检查.例如 'constructor' in myObj
是真的,但 myObj.hasOwnProperty('constructor')
不是.
Note that hasOwnProperty
doesn't check for inherited properties, whereas in
does. For example 'constructor' in myObj
is true, but myObj.hasOwnProperty('constructor')
is not.
这篇关于如何使用保存属性名称的变量检查对象属性是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文