774

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

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

4

10 回答 10

1469
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')不是。

于 2012-06-14T20:01:03.240 回答
58

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

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

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

另一种方法是使用in运算符,但您也需要在此处使用引号

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

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

于 2015-05-10T07:22:07.810 回答
25

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

其中每一个都是变量:appChoice、underI、underObstr。

if(typeof tData.tonicdata[appChoice][underI][underObstr] !== "undefined"){
    //enter code here
}
于 2012-06-15T15:15:56.800 回答
24

对于自己的财产:

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

注意:使用Object.prototype.hasOwnProperty比 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运算符:(但您必须在 '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

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

var loan = { amount: 150 };

loan.installment = undefined;

if("installment" in loan) // correct
{
    // will execute
}

if(typeof loan["installment"] !== "undefined") // incorrect
{
    // will not execute
}
于 2017-10-15T12:57:34.460 回答
14

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

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

于 2016-07-25T12:36:57.800 回答
5

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

于 2015-11-07T15:38:09.343 回答
2

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

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.
于 2020-11-04T22:42:19.697 回答
2

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

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

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

var myBadObj = undefined;
var myGoodObj = {prop:"exists"}
var myProp = "prop";

//1 use brackets. 
myGoodObj.myProp && console.log("wrong"); //dot is incorrect here
//(myBadObj[myProp]) //this would throw because undefined
myGoodObj[myProp] && console.log("1 - yes, i have that property");

// 2 use optional chaining.  tolerates undefined myBadObj
myBadObj?.[myProp] && console.log("2 - myBadObj has that");
myGoodObj?.[myProp] && console.log("2 - myGoodObj has that");

//3 get a boolean from the truthy value
console.log(3, !!myBadObj?.[myProp]);
console.log(3, !!myGoodObj?.[myProp]); 

//4 use in operator
//console.log(4, myProp in myBadObj); // would throw
console.log(4, myProp in {prop:undefined});
console.log(4, myProp in myGoodObj);
console.log(4, myProp in (myBadObj ?? {}));

//5 probably don't use hasOwnProperty()
myProp = "hasOwnProperty";
// doesn't catch inherited properties (ex: hasOwnProperty is itself inherited)
console.log(5, myGoodObj.hasOwnProperty(myProp)); // false :(
// intolerant of undefined obj
console.log(5, myBadObj.hasOwnProperty(myProp)); // throws because undefined :(

于 2021-06-30T23:12:01.527 回答
1

使用该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

于 2021-09-28T10:23:20.847 回答
-1

在答案中我没有看到!!操作员

if (!!myObj.myProp) //Do something

于 2021-05-04T16:25:12.937 回答