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

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

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

827814 次浏览
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')不是。

感谢大家的帮助和推动,以摆脱Aval声明。变量需要放在括号中,而不是点表示法。这很有效,并且是干净、正确的代码。

这些都是变量:appChoice、underI、underObstr。

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

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

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

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

另一种方法是使用运算符,但这里也需要报价

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

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

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

检查对象上是否存在属性的更安全的方法是使用空对象或对象原型调用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 purposeObject.prototype.hasOwnProperty.call(foo, 'bar'); // true

引用自MDN Web Docs-Object.prototype.hasOwnProperty()

对于自己的财产:

var loan = { amount: 150 };if(Object.prototype.hasOwnProperty.call(loan, "amount")){//will execute}

注意:使用Object.prototype.has所有权比loan.hasOwnProperty(…)更好,以防在原型链中定义了自定义hasOwnProperty(这里不是这种情况),例如

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

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

要在查找中包含继承的属性,请使用运算符:(但您必须在'in'的右侧放置一个对象,原始值会抛出错误,例如home中的长度会抛出错误,但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

注意:人们可能会试图使用typeof和[]属性访问器作为以下代码,其中并不总是有效

var loan = { amount: 150 };
loan.installment = undefined;
if("installment" in loan) // correct{// will execute}
if(typeof loan["installment"] !== "undefined") // incorrect{// will not execute}

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

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

有更简单的解决方案,我看不到你实际问题的任何答案:

“它正在寻找myObj.my道具,但我希望它检查myObj.prop

  1. 要从变量中获取属性值,请使用括号符号
  2. 要测试该属性的真值,请使用可选链接
  3. 要返回布尔值,请使用双不/砰-砰/(!!)
  4. 如果您确定您有一个对象并且只想检查该属性的存在(即使prop值未定义,也可以使用#0运算符)。或者与零合并算子??组合以避免抛出错误。

var nothing = undefined;var obj = {prop:"hello world"}var myProp = "prop";
consolelog( 1,()=> obj.myProp); // obj does not have a "myProp"consolelog( 2,()=> obj[myProp]); // brackets worksconsolelog( 3,()=> nothing[myProp]); // throws if not an objectconsolelog( 4,()=> obj?.[myProp]); // optional chaining very nice ⭐️⭐️⭐️⭐️⭐️consolelog( 5,()=> nothing?.[myProp]); // optional chaining avoids throwingconsolelog( 6,()=> nothing?.[nothing]); // even here it is error-safeconsolelog( 7,()=> !!obj?.[myProp]); // double-not yields trueconsolelog( 8,()=> !!nothing?.[myProp]); // false because undefinedconsolelog( 9,()=> myProp in obj); // in operator worksconsolelog(10,()=> myProp in nothing); // throws if not an objectconsolelog(11,()=> myProp in (nothing ?? {})); // safe from throwingconsolelog(12,()=> myProp in {prop:undefined}); // true (prop key exists even though its value undefined)
// beware of 'hasOwnProperty' pitfalls// it can't detect inherited properties and 'hasOwnProperty' is itself inherited// also comparatively verboseconsolelog(13,()=> obj.hasOwnProperty("hasOwnProperty")); // DANGER: it yields falseconsolelog(14,()=> nothing.hasOwnProperty("hasOwnProperty")); // throws when undefined
function consolelog(num,myTest){try{console.log(num,myTest());}catch(e){console.log(num,'throws',e.message);}}

使用新的Object.hasOwn方法也是一种选择,它的目的是取代Object.hasOwnProperty方法。

如果指定对象将指定的属性作为其自己的属性,则此静态方法返回true;如果该属性是继承的或该对象上不存在,则返回false。

请不要在生产中使用它之前仔细检查浏览器兼容性表,因为它仍然被认为是一项实验技术,尚未被所有浏览器完全支持(尽管很快就会支持)

    var myObj = {};myObj.myProp = "exists";
if (Object.hasOwn(myObj, 'myProp')){alert("yes, i have that property");}

更多关于Object.hasOwn-https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn

Object.hasOwn浏览器兼容性-https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn#browser_compatibility