本文翻译自: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");
};
This is undefined
because it's looking for myObj.myProp
but I want it to check for myObj.prop
这是undefined
因为它正在寻找myObj.myProp
但我希望它检查myObj.prop
#1楼
参考:https://stackoom.com/question/kK88/如何使用包含属性名称的变量检查对象属性是否存在
#2楼
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");
}
Note that hasOwnProperty
doesn't check for inherited properties, whereas in
does. 请注意, hasOwnProperty
不检查继承的属性,而in
。 For example 'constructor' in myObj
is true, but myObj.hasOwnProperty('constructor')
is not. 例如'constructor' in myObj
为true,但myObj.hasOwnProperty('constructor')
不是。
#3楼
Thank you for everyone's assistance and pushing to get rid of the eval statement. 感谢大家的帮助,并推动摆脱eval声明。 Variables needed to be in brackets, not dot notation. 变量必须在括号中,而不是点符号。 This works and is clean, proper code. 这是有效的,干净,正确的代码。
Each of these are variables: appChoice, underI, underObstr. 其中每个都是变量:appChoice,underI,underObstr。
if(typeof tData.tonicdata[appChoice][underI][underObstr] !== "undefined"){
//enter code here
}
#4楼
You can use hasOwnProperty , but based on the reference you need quotes when using this method: 您可以使用hasOwnProperty ,但根据引用,您在使用此方法时需要引用 :
if (myObj.hasOwnProperty('myProp')) {
// do something
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty
Another way is to use in operator, but you need quotes here as well: 另一种方法是在运算符中使用,但这里也需要引号 :
if ('myProp' in myObj) {
// do something
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in
#5楼
您可以使用hasOwnProperty()
以及in
运营商。
#6楼
A much more secure way to check if property exists on the object is to use empty object or object prototype to call hasOwnProperty()
检查对象上是否存在属性的更安全的方法是使用空对象或对象原型来调用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
Reference from MDN Web Docs - Object.prototype.hasOwnProperty() 来自MDN Web Docs的参考- Object.prototype.hasOwnProperty()