如何检查JavaScript对象或数组中是否存在特定键?
如果密钥不存在,并且我试图访问它,它会返回false吗?或者抛出错误?
如何检查JavaScript对象或数组中是否存在特定键?
如果密钥不存在,并且我试图访问它,它会返回false吗?或者抛出错误?
当前回答
在“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]);
其他回答
检查javascript对象中是否存在属性的三种方法:
!!对象.属性将值转换为布尔值。对于除false值之外的所有值返回true对象中的“属性”如果属性存在,无论其值如何(甚至为空),都将返回trueobj.hasOwnProperty(“属性”)不检查原型链。(由于所有对象都有toString方法,因此1和2将返回true,而3可以返回false。)
参考:
http://book.mixu.net/node/ch5.html
const rawObject = {};
rawObject.propertyKey = 'somethingValue';
console.log(rawObject.hasOwnProperty('somethingValue'));
// expected output: true
检查给定对象中存在的特定键,hasOwnProperty将在此处工作。
检查对象的财产,包括继承的财产
无法使用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
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
如果在项目中配置了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));