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

var myObj;
myObj.prop = "exists";
var myProp = "p"+"r"+"o"+"p";

if(myObj.myProp){
    alert("yes, i have that property");
};

这是未定义的,因为它正在查找myObj.myrop,但我希望它检查myObj.rop


当前回答

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

其他回答

您可以使用hasOwnProperty,但根据引用,使用此方法时需要引号:

if (myObj.hasOwnProperty('myProp')) {
    // do something
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

另一种方法是使用in运算符,但这里也需要引号:

if ('myProp' in myObj) {
    // do something
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in

为我工作。

if (typeof receviedData?.d?.heartbeat_interval != "undefined") {
}

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

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

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

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

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

检查对象上是否存在属性的更安全的方法是使用空对象或对象原型来调用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()