如何使用包含属性名称的变量检查对象属性是否存在?

如何使用包含属性名称的变量检查对象属性是否存在?

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


var myObj;

myObj.prop = "exists";

var myProp = "p"+"r"+"o"+"p";


if(myObj.myProp){

    alert("yes, i have that property");

};

这是undefined因为它正在寻找,myObj.myProp但我希望它来检查myObj.prop


慕沐林林
浏览 445回答 3
3回答

慕容708150

var myProp = 'prop';if(myObj.hasOwnProperty(myProp)){     alert("yes, i have that property");}要么var myProp = 'prop';if(myProp in myObj){     alert("yes, i have that property");}要么if('prop' in myObj){     alert("yes, i have that property");}请注意,hasOwnProperty不会检查继承的属性,而是检查in。例如'constructor' in myObj是真的,但事实myObj.hasOwnProperty('constructor')并非如此。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript