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

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


当前回答

使用“反射”的替代方法

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

其他回答

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

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

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

此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}));//假的

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

JavaScript Destructuring的新解决方案:

let obj = {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3",
};

let {key1, key2, key3, key4} = obj;

// key1 = "value1"
// key2 = "value2"
// key3 = "value3"
// key4 = undefined

// Can easily use `if` here on key4
if(!key4) { console.log("key not present"); } // Key not present

检查JavaScript Destructuring的其他用法

香草js

yourObjName.hasOwnProperty(key) : true ? false;

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

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

值得注意的是,自从引入ES11以来,您可以使用零合并运算符,这大大简化了事情:

const obj = {foo: 'one', bar: 'two'};

const result = obj.foo ?? "Not found";

上面的代码将为foo中的任何“falsy”值返回“Not found”。否则将返回obj.foo。

请参见与零合并运算符组合