我正在检查是否存在一个对象属性,该属性包含一个变量,该变量包含有问题的属性名称。
var myObj;
myObj.prop = "exists";
var myProp = "p"+"r"+"o"+"p";
if(myObj.myProp){
alert("yes, i have that property");
};
这是未定义的,因为它正在查找myObj.myrop,但我希望它检查myObj.rop
我正在检查是否存在一个对象属性,该属性包含一个变量,该变量包含有问题的属性名称。
var myObj;
myObj.prop = "exists";
var myProp = "p"+"r"+"o"+"p";
if(myObj.myProp){
alert("yes, i have that property");
};
这是未定义的,因为它正在查找myObj.myrop,但我希望它检查myObj.rop
当前回答
var myProp = 'prop';
if(myObj.hasOwnProperty(myProp)){
alert("yes, i have that property");
}
Or
var myProp = 'prop';
if(myProp in myObj){
alert("yes, i have that property");
}
Or
if('prop' in myObj){
alert("yes, i have that property");
}
请注意,hasOwnProperty不检查继承的财产,而in检查继承的属性。例如,myObj中的“constructor”为true,但myObj.hasOwnProperty(“constructors”)不是。
其他回答
在答案中,我没有看到!!真实性检查。
if (!!myObj.myProp) //Do something
var myProp = 'prop';
if(myObj.hasOwnProperty(myProp)){
alert("yes, i have that property");
}
Or
var myProp = 'prop';
if(myProp in myObj){
alert("yes, i have that property");
}
Or
if('prop' in myObj){
alert("yes, i have that property");
}
请注意,hasOwnProperty不检查继承的财产,而in检查继承的属性。例如,myObj中的“constructor”为true,但myObj.hasOwnProperty(“constructors”)不是。
为我工作。
if (typeof receviedData?.d?.heartbeat_interval != "undefined") {
}
感谢大家的帮助,并推动消除eval声明。变量需要放在括号中,而不是点符号。这是一个干净、正确的代码。
其中每个都是变量:appChoice、underI、underObst。
if(typeof tData.tonicdata[appChoice][underI][underObstr] !== "undefined"){
//enter code here
}
您可以使用hasOwnProperty()和in运算符。