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

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


当前回答

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';

其他回答

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

布尔(obj.foo)

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

如果在项目中配置了ESLint,则遵循ESLint规则,没有内置原型。以下链接描述了原因:

// bad
console.log(object.hasOwnProperty(key));

// good
console.log(Object.prototype.hasOwnProperty.call(object, key));

// best
const has = Object.prototype.hasOwnProperty; // cache the lookup once, in module scope.
console.log(has.call(object, key));
/* or */
import has from 'has'; // https://www.npmjs.com/package/has
console.log(has(object, key));

检查javascript对象中是否存在属性的三种方法:

!!对象.属性将值转换为布尔值。对于除false值之外的所有值返回true对象中的“属性”如果属性存在,无论其值如何(甚至为空),都将返回trueobj.hasOwnProperty(“属性”)不检查原型链。(由于所有对象都有toString方法,因此1和2将返回true,而3可以返回false。)

参考:

http://book.mixu.net/node/ch5.html

香草js

yourObjName.hasOwnProperty(key) : true ? false;

如果要检查对象在es2015中是否至少有一个属性

Object.keys(yourObjName).length : true ? false

它将返回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
}