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

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


当前回答

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

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

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

其他回答

如果在项目中配置了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));

接受的答案指的是对象。小心使用Array上的in运算符查找数据而不是键:

("true" in ["true", "false"])
// -> false (Because the keys of the above Array are actually 0 and 1)

测试数组中的现有元素:查找项目是否在JavaScript数组中的最佳方法?

使用“反射”的替代方法

根据MDN

Reflect是一个内置对象,它提供可拦截的方法JavaScript操作。静态Reflect.has()方法的工作方式类似于in运算符作用

变量obj={a: 未定义,b: 1中,c: “hello world”}console.log(Reflect.has(obj,“a”))console.log(Reflect.has(obj,'b'))console.log(Reflect.has(obj,“c”))console.log(Reflect.has(obj,“d”))

我应该使用它吗?

这取决于。

Reflect.has()比公认答案中提到的其他方法慢(根据我的基准测试)。但是,如果您只在代码中使用它几次,我看不出这种方法有多大问题。

可选链接运算符:

常量发票={客户:{地址:{城市:“foo”}}console.log(发票?.客户?.地址?.城市)console.log(发票?.客户?.地址?.街道)console.log(发票?.xyz?.address?.city)

查看支持的浏览器列表


对于那些在项目中包含lodash的人:有一个lodash_.get方法,它试图获取“深层”键:

获取对象路径处的值。如果解析值未定义,在其位置返回defaultValue。

var对象={‘a’:〔{‘b’:{‘c’:3}}〕};控制台日志(_.get(对象,'a[0].b.c'),//=>3_.get(对象,['a','0','b','c']),//=>3_.get(对象,'a.b.c'),//=>未定义_.get(对象,'a.b.c','default')//=>'default')<script src=“https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js“></script>


这将有效地检查是否定义了该键,无论该键有多深,如果未定义该键,则不会引发可能会损害程序流的错误。

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

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

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