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

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


当前回答

检查对象的财产,包括继承的财产

无法使用in运算符确定,如果指定的属性位于指定的对象或其原型链中,则返回true,否则返回false

const person={name:“dan”};console.log(“姓名”亲自填写);//真的console.log(“页面”);//假的

检查对象实例的财产(不包括继承的财产)

*2021-使用新方法***Object.hasOwn()替换Object.hasOwnProperty()

Object.hasOwn()是Object.hasOwnerProperty()的替代品,是一种新的方法(目前尚不完全受safari等所有浏览器的支持,但很快就会得到支持)

Object.hasOwn()是一个静态方法,如果指定的对象具有指定的属性作为其自身的属性,则返回true。如果属性是继承的或不存在的,则该方法返回false。

const person={name:“dan”};console.log(Object.hasOwn(person,'name'));//真的console.log(Object.hasOwn(person,'age'));//假的const person2=Object.create({gender:“male”});console.log(Object.hasOwn(person2,'gender'));//假的

在Object.prototype.hasOwnProperty上使用它的动机是什么?-建议在Object.hasOwnProperty()上使用此方法,因为它也适用于使用Object.create(null)创建的对象以及已重写继承的hasOwnProperty方法的对象。虽然可以通过对外部对象调用Object.product.hasOwnProperty()来解决这类问题,但Object.hasOwn()克服了这些问题,因此是首选(参见下面的示例)

让人={hasOwnProperty:函数(){return false;},年龄:35岁};if(Object.hasOwn(人,'年龄')){console.log(person.age);//true-hasOwnProperty()的重新实现不会影响对象}

let person=Object.create(null);人年龄=35岁;if(Object.hasOwn(人,'年龄')){console.log(person.age);//true-无论对象是如何创建的都有效}

有关Object.hasOwn的更多信息,请访问:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn

Object.hasOwn的浏览器兼容性-https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn#browser_compatibility

其他回答

可选链接运算符:

常量发票={客户:{地址:{城市:“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>


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

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

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

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

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

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

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

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