Javascript 如何使用保存属性名称的变量检查对象属性是否存在?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11040472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if object property exists with a variable holding the property name?
提问by Slopeside Creative
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
回答by Rocket Hazmat
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. For example 'constructor' in myObj
is true, but myObj.hasOwnProperty('constructor')
is not.
请注意,hasOwnProperty
它不会检查继承的属性,而in
会检查。例如'constructor' in myObj
是真的,但myObj.hasOwnProperty('constructor')
不是。
回答by Adorjan Princz
You can use hasOwnProperty, but based on the reference you need quoteswhen using this method:
您可以使用hasOwnProperty,但根据参考,使用此方法时需要引号:
if (myObj.hasOwnProperty('myProp')) {
// do something
}
Another way is to use inoperator, but you need quoteshere as well:
另一种方法是使用in运算符,但这里也需要引号:
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
回答by Slopeside Creative
Thank you for everyone's assistance and pushing to get rid of the eval statement. Variables needed to be in brackets, not dot notation. This works and is clean, proper code.
感谢大家的帮助和推动摆脱 eval 语句。变量需要在括号中,而不是点符号。这有效并且是干净,正确的代码。
Each of these are variables: appChoice, underI, underObstr.
每一个都是变量:appChoice、underI、underObstr。
if(typeof tData.tonicdata[appChoice][underI][underObstr] !== "undefined"){
//enter code here
}
回答by adnan2nd
For own property :
对于自有财产:
var loan = { amount: 150 };
if(Object.prototype.hasOwnProperty.call(loan, "amount"))
{
//will execute
}
Note: using Object.prototype.hasOwnPropertyis better than loan.hasOwnProperty(..), in case a custom hasOwnProperty is defined in the prototype chain (which is not the case here), like
注意:使用Object.prototype.hasOwnProperty比 Loan.hasOwnProperty(..) 好,以防在原型链中定义了自定义 hasOwnProperty(这里不是这种情况),例如
var foo = {
hasOwnProperty: function() {
return false;
},
bar: 'Here be dragons'
};
To include inherited properties in the finding use the inoperator: (but you must place an object at the right side of 'in', primitive values will throw error, e.g. 'length' in 'home'will throw error, but 'length' in new String('home')won't)
要在发现中包含继承的属性,请使用in运算符:(但您必须在 'in' 的右侧放置一个对象,原始值将抛出错误,例如 'home' 中的 'length'将抛出错误,但'length'在 new String('home') 中不会)
const yoshi = { skulk: true };
const hattori = { sneak: true };
const kuma = { creep: true };
if ("skulk" in yoshi)
console.log("Yoshi can skulk");
if (!("sneak" in yoshi))
console.log("Yoshi cannot sneak");
if (!("creep" in yoshi))
console.log("Yoshi cannot creep");
Object.setPrototypeOf(yoshi, hattori);
if ("sneak" in yoshi)
console.log("Yoshi can now sneak");
if (!("creep" in hattori))
console.log("Hattori cannot creep");
Object.setPrototypeOf(hattori, kuma);
if ("creep" in hattori)
console.log("Hattori can now creep");
if ("creep" in yoshi)
console.log("Yoshi can also creep");
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in
Note: One may be tempted to use typeof and [ ] property accessor as the following code which doesn't work always...
注意:人们可能会尝试使用 typeof 和 [ ] 属性访问器作为以下代码,这并不总是有效......
var loan = { amount: 150 };
loan.installment = undefined;
if("installment" in loan) // correct
{
// will execute
}
if(typeof loan["installment"] !== "undefined") // incorrect
{
// will not execute
}
回答by skmasq
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()
回答by Simran Kaur
You can use hasOwnProperty()
as well as in
operator.
您可以使用hasOwnProperty()
以及in
运算符。