如何在javascript中检查对象中是否存在键[重复]

时间:2021-09-24 11:52:47

This question already has an answer here:

这个问题在这里已有答案:

I have the following object literal:

我有以下对象文字:

{ 
  'key1': 
  { 
    id: 'rr323',
    d: undefined,
    x: 560,
    y: 150 
  },
  'key2': 
  { 
    id: 'rr231',
    d: undefined,
    x: 860,
    y: 90 
  } 
}

I want to implement an if statement such as below:

我想实现一个if语句,如下所示:

if(key DOES NOT exist in object){  
//perform certain function 
}

I tried the following:

我尝试了以下方法:

var key = key1;
if(!(key in global_move_obj)){
 // function
}

But that always returns true value when it should return false.

但是当它应该返回false时,它总是返回true值。

2 个解决方案

#1


6  

Use the hasOwnProperty call

使用hasOwnProperty调用

if (!obj.hasOwnProperty(key)) {

}

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

#2


0  

You can do it like:

你可以这样做:

var key = 'key1';
if (!('key1' in obj)) {
    ....
} 
// or
if (!(key in obj)) {

}

#1


6  

Use the hasOwnProperty call

使用hasOwnProperty调用

if (!obj.hasOwnProperty(key)) {

}

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

#2


0  

You can do it like:

你可以这样做:

var key = 'key1';
if (!('key1' in obj)) {
    ....
} 
// or
if (!(key in obj)) {

}