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

Slo*_*ive 619 javascript object

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

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

if(myObj.myProp){
    alert("yes, i have that property");
};
Run Code Online (Sandbox Code Playgroud)

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

Roc*_*mat 1209

var myProp = 'prop';
if(myObj.hasOwnProperty(myProp)){
    alert("yes, i have that property");
}
Run Code Online (Sandbox Code Playgroud)

要么

var myProp = 'prop';
if(myProp in myObj){
    alert("yes, i have that property");
}
Run Code Online (Sandbox Code Playgroud)

要么

if('prop' in myObj){
    alert("yes, i have that property");
}
Run Code Online (Sandbox Code Playgroud)

  • `hasOwnProperty()`比`myObj [myProp]`(来自其他答案)更好,因为即使`myProp`的值为0也能正常工作 (20认同)
  • "in"运算符不适用于字符串.例如'qqq'中的'length'会产生异常.因此,如果您想要进行通用检查,则需要使用hasOwnProperty. (8认同)
  • 为了避免破坏 eslint `no-prototype-builtins` 规则,您应该使用 `Object.prototype.hasOwnProperty.call(myObj, myProp)` 而不是 `myObj.hasOwnProperty(myProp)` (3认同)
  • @Jacob当你说““in”运算符不适用于字符串时,你的意思是什么?对于“in”运算符,左侧表达式必须是字符串或可以转换为字符串的值。是的,你不能在 'qqq' 中写 'length' 但你也不能写 'qqq'.hasOwnProperty('length') (2认同)
  • @Wachburn:`'qqq'.hasOwnProperty('length')` 是 `true`,你可以这样做。 (2认同)

Ado*_*ncz 43

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

if (myObj.hasOwnProperty('myProp')) {
    // do something
}
Run Code Online (Sandbox Code Playgroud)

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

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

if ('myProp' in myObj) {
    // do something
}
Run Code Online (Sandbox Code Playgroud)

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

  • 这是不正确的.通过在名称myProp周围加上引号,您不再引用myProp的值,而是声明'myProp'的新String()并且myObj中没有'myProp'这样的属性. (7认同)
  • 那是[**not**](http://jsfiddle.net/s8eegdry/1)如何实现`hasOwnProperty()`. (5认同)

Slo*_*ive 24

感谢大家的帮助,并推动摆脱eval声明.变量必须在括号中,而不是点符号.这是有效的,干净,正确的代码.

其中每个都是变量:appChoice,underI,underObstr.

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

  • 尽管您最初发布帖子的意图,但实际上您提出的问题与您提供此答案的问题不同。您想要检查某个属性是否存在,但没有提及有关如何访问它的任何内容。这使得这个答案与实际问题无关。 (2认同)

bri*_*web 12

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

\n
\n

“它正在寻找 myObj.myProp,但我希望它检查 myObj.prop”

\n
\n
    \n
  1. 要从变量获取属性值,请使用方括号表示法
  2. \n
  3. 要测试该属性的真实值,请使用可选\n链接
  4. \n
  5. 要返回布尔值,请使用double-not / bang-bang / (!!)
  6. \n
  7. 如果您确定有一个对象并且只想检查该属性是否存在(即使 prop 值未定义),请使用该in运算符。true或者也许与空值合并运算符结合使用?以避免引发错误。
  8. \n
\n

\r\n
\r\n
var nothing = undefined;\nvar obj = {prop:"hello world"}\nvar myProp = "prop";\n\nconsolelog( 1,()=> obj.myProp); // obj does not have a "myProp"\nconsolelog( 2,()=> obj[myProp]); // brackets works\nconsolelog( 3,()=> nothing[myProp]); // throws if not an object\nconsolelog( 4,()=> obj?.[myProp]); // optional chaining very nice \xe2\xad\x90\xef\xb8\x8f\xe2\xad\x90\xef\xb8\x8f\xe2\xad\x90\xef\xb8\x8f\xe2\xad\x90\xef\xb8\x8f\xe2\xad\x90\xef\xb8\x8f\nconsolelog( 5,()=> nothing?.[myProp]); // optional chaining avoids throwing\nconsolelog( 6,()=> nothing?.[nothing]); // even here it is error-safe\nconsolelog( 7,()=> !!obj?.[myProp]); // double-not yields true\nconsolelog( 8,()=> !!nothing?.[myProp]); // false because undefined\nconsolelog( 9,()=> myProp in obj); // in operator works\nconsolelog(10,()=> myProp in nothing); // throws if not an object\nconsolelog(11,()=> myProp in (nothing ?? {})); // safe from throwing\nconsolelog(12,()=> myProp in {prop:undefined}); // true (prop key exists even though its value undefined)\n\n// beware of \'hasOwnProperty\' pitfalls\n// it can\'t detect inherited properties and \'hasOwnProperty\' is itself inherited\n// also comparatively verbose\nconsolelog(13,()=> obj.hasOwnProperty("hasOwnProperty")); // DANGER: it yields false \nconsolelog(14,()=> nothing.hasOwnProperty("hasOwnProperty")); // throws when undefined\nobj.hasOwnProperty = ()=>true; // someone could overwrite it\nconsolelog(15,()=> obj.hasOwnProperty(nothing)); // DANGER: the foolish overwrite will now always return true\nconsolelog(16,()=> Object.prototype.hasOwnProperty.call(obj,"hasOwnProperty")); // explain?!\nconsolelog(17,()=> Object.hasOwn(obj,"hasOwnProperty")); // explain?!\n\nfunction consolelog(num,myTest){\n    try{\n    console.log(num,myTest());\n    }\n    catch(e){\n    console.log(num,\'throws\',e.message);\n    }\n}
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n


adn*_*2nd 11

对于自己的财产:

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

注意:使用Object.prototype.hasOwnProperty优于loan.hasOwnProperty(..),以防在原型链中定义自定义hasOwnProperty(这不是这里的情况),如

var foo = {
      hasOwnProperty: function() {
        return false;
      },
      bar: 'Here be dragons'
    };
Run Code Online (Sandbox Code Playgroud)

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

要在查找中包含继承属性,请使用in运算符:(但是必须将对象放在'in'的右侧,原始值将抛出错误,例如 'home'中的'length'将抛出错误,但'length' in 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");
Run Code Online (Sandbox Code Playgroud)

// 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
}
Run Code Online (Sandbox Code Playgroud)


skm*_*asq 10

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

来自MDN Web Docs的参考- Object.prototype.hasOwnProperty()

  • 如果您合并的JavaScript可能会做一些恶作剧,例如覆盖`hasOwnProperty`,那么没有多少保护措施可以使您的代码安全。 (2认同)

Sim*_*aur 5

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

  • 所有这些 ^ 就是我讨厌 javascript 的原因 (4认同)
  • @pwaterz 不讨厌[玩家](https://giphy.com/search/javascript) (2认同)
  • 正如 Rocket Hazmat 的回答所解释的那样,“hasOwnProperty”并不等同于使用“in”运算符。 (2认同)

Ran*_*ner 5

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

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

请注意,在生产中使用它之前,您必须仔细检查浏览器兼容性表,因为它仍然被认为是一种实验性技术,并且尚未得到所有浏览器的完全支持(但很快就会得到支持)

var myObj = {};
myObj.myProp = "exists";

if (Object.hasOwn(myObj, 'myProp')) {
  alert("yes, i have that property");
}
Run Code Online (Sandbox Code Playgroud)

更多关于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