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

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


当前回答

"key" in obj

可能只测试与数组键非常不同的对象属性值

其他回答

在“array”世界中,我们可以将索引视为某种键。令人惊讶的是,in运算符(这是对象的好选择)也适用于数组。不存在键的返回值未定义

设arr=[“a”,“b”,“c”];//我们有索引:0,1,2删除arr[1];//在索引1处设置“空”arr.pop();//删除最后一项console.log(arr中的0,arr[0]);console.log(arr中的1,arr[1]);console.log(arr中的2,arr[2]);

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 

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

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

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

无法使用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

要查找对象中是否存在键,请使用

对象.keys(obj).includes(key)

ES7包括检查数组是否包含项的方法,这是indexOf的一种更简单的替代方法。