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

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


当前回答

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

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

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

其他回答

如果您使用的是underscore.js库,那么对象/数组操作就变得简单了。

在您的情况下,可以使用_.has方法。例子:

yourArray = {age: "10"}

_.has(yourArray, "age")

返回true

But,

_.has(yourArray, "invalidKey")

返回false

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

使用“反射”的替代方法

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

这里有一个我觉得很有用的助手函数

此keyExists(key,search)可用于轻松查找对象或数组中的键!

只需将要查找的键传递给它,然后搜索要查找它的obj(对象或数组)。

函数keyExists(键,搜索){if(!search||(search.constructor!==数组&&search.constructionr!==对象)){return false;}for(var i=0;i<search.length;i++){if(搜索[i]==键){返回true;}}搜索中的返回键;}//如何使用://在数组中搜索关键字console.log(keyExists('apple',[apple','banana','orange']);//真的console.log(keyExists('水果',[苹果','香蕉','橙色']);//假的//在对象中搜索关键字console.log(keyExists('age',{'name':'Bill','age':29}));//真的console.log(keyExists('title',{'name':'Jason','age':29}));//假的

它非常可靠,跨浏览器运行良好。

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

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