我正在检查是否存在一个对象属性,该属性包含一个变量,该变量包含有问题的属性名称。

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”)不是。

其他回答

检查对象上是否存在属性的更安全的方法是使用空对象或对象原型来调用hasOwnProperty()

var foo = {
  hasOwnProperty: function() {
    return false;
  },
  bar: 'Here be dragons'
};

foo.hasOwnProperty('bar'); // always returns false

// Use another Object's hasOwnProperty and call it with 'this' set to foo
({}).hasOwnProperty.call(foo, 'bar'); // true

// It's also possible to use the hasOwnProperty property from the Object
// prototype for this purpose
Object.prototype.hasOwnProperty.call(foo, 'bar'); // true

来自MDN Web Docs的引用-Object.protype.hasOwnProperty()

您可以使用hasOwnProperty()和in运算符。

检查对象属性是否存在的几种方法。

const dog = { name: "Spot" }

if (dog.name) console.log("Yay 1"); // Prints.
if (dog.sex) console.log("Yay 2"); // Doesn't print. 

if ("name" in dog) console.log("Yay 3"); // Prints.
if ("sex" in dog) console.log("Yay 4"); // Doesn't print.

if (dog.hasOwnProperty("name")) console.log("Yay 5"); // Prints.
if (dog.hasOwnProperty("sex")) console.log("Yay 6"); // Doesn't print, but prints undefined.

在答案中,我没有看到!!真实性检查。

if (!!myObj.myProp) //Do something

感谢大家的帮助,并推动消除eval声明。变量需要放在括号中,而不是点符号。这是一个干净、正确的代码。

其中每个都是变量:appChoice、underI、underObst。

if(typeof tData.tonicdata[appChoice][underI][underObstr] !== "undefined"){
    //enter code here
}