如何检查JavaScript对象或数组中是否存在特定键?

如果密钥不存在,并且我试图访问它,它会返回false吗?或者抛出错误?


当前回答

最简单的检查方法是

"key" in object

例如:

var obj = {
  a: 1,
  b: 2,
}
"a" in obj // true
"c" in obj // false

返回值true表示对象中存在键。

其他回答

这些例子可以说明不同方式之间的差异。希望它能帮助您选择适合您需求的产品:

// Lets create object `a` using create function `A`
function A(){};
A.prototype.onProtDef=2;
A.prototype.onProtUndef=undefined;
var a=new A();
a.ownProp = 3;
a.ownPropUndef = undefined;

// Let's try different methods:

a.onProtDef; // 2
a.onProtUndef; // undefined
a.ownProp; // 3
a.ownPropUndef; // undefined
a.whatEver; // undefined
a.valueOf; // ƒ valueOf() { [native code] }

a.hasOwnProperty('onProtDef'); // false
a.hasOwnProperty('onProtUndef'); // false
a.hasOwnProperty('ownProp'); // true
a.hasOwnProperty('ownPropUndef'); // true
a.hasOwnProperty('whatEver'); // false
a.hasOwnProperty('valueOf'); // false

'onProtDef' in a; // true
'onProtUndef' in a; // true
'ownProp' in a; // true
'ownPropUndef' in a; // true
'whatEver' in a; // false
'valueOf' in a; // true (on the prototype chain - Object.valueOf)

Object.keys(a); // ["ownProp", "ownPropUndef"]

yourArray.indexOf(yourArrayKeyName)>-1

fruit = ['apple', 'grapes', 'banana']

fruit.indexOf('apple') > -1

true


fruit = ['apple', 'grapes', 'banana']

fruit.indexOf('apple1') > -1

假的


对于严格的对象键检查:

const object1 = {};
object1.stackoverflow = 51; 
console.log(object1.hasOwnProperty('stackoverflow')); 



output: true 

在我的例子中,我想检查LUIS返回的NLP元数据,它是一个对象。我想检查一个字符串“FinancialRiskIntent”的键是否作为元数据对象中的键存在。

我试图将需要检查的嵌套对象作为目标->data.meta.precision.intents(仅出于我自己的目的,您的对象可以是任何对象)我使用以下代码检查密钥是否存在:

const hasKey=data.meta.prprediction.intents中的“财务风险意图”;if(hasKey){console.log('密钥存在。');}其他{console.log('密钥不存在。');}

这是在检查我最初寻找的特定密钥。

希望这一点对某人有所帮助。

const rawObject = {};
rawObject.propertyKey = 'somethingValue';

console.log(rawObject.hasOwnProperty('somethingValue'));
// expected output: true

检查给定对象中存在的特定键,hasOwnProperty将在此处工作。

const object1 = {
  a: 'something',
  b: 'something',
  c: 'something'
};

const key = 's';

// Object.keys(object1) will return array of the object keys ['a', 'b', 'c']

Object.keys(object1).indexOf(key) === -1 ? 'the key is not there' : 'yep the key is exist';