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

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


当前回答

虽然这不一定检查键是否存在,但它确实检查值的真实性。其中未定义和空值属于。

布尔(obj.foo)

这个解决方案最适合我,因为我使用了typescript,并且在obj或obj.hasOwnProperty('fo')中使用了像so'foo'这样的字符串检查密钥是否存在并不能为我提供智能感知。

其他回答

要查找对象中是否存在键,请使用

对象.keys(obj).includes(key)

ES7包括检查数组是否包含项的方法,这是indexOf的一种更简单的替代方法。

它将返回undefined。

var aa={hello:“world”};警报(aa[“hello”]);//带有“world”的弹出框警报(aa[“再见”]);//带有“未定义”的弹出框

undefined是一个特殊的常量值。所以你可以说,例如。

// note the three equal signs so that null won't be equal to undefined
if( aa["goodbye"] === undefined ) {
    // do something
}

这可能是检查丢失钥匙的最佳方法。然而,正如下面的评论所指出的,理论上,您可能希望未定义实际值。我从来都不需要这样做,也无法马上想到我想要这样做的原因,但为了完整起见,您可以使用in运算符

// this works even if you have {"goodbye": undefined}
if( "goodbye" in aa ) {
    // do something
}

我们可以使用-hasOwnProperty.call(obj,key);

underscore.js方式-

if(_.has(this.options, 'login')){
  //key 'login' exists in this.options 
}

_.has = function(obj, key) {
  return hasOwnProperty.call(obj, key);
};

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

// 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