如何检查JavaScript对象或数组中是否存在特定键?
如果密钥不存在,并且我试图访问它,它会返回false吗?或者抛出错误?
如何检查JavaScript对象或数组中是否存在特定键?
如果密钥不存在,并且我试图访问它,它会返回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));
其他回答
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
可选链接运算符:
常量发票={客户:{地址:{城市:“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>
这将有效地检查是否定义了该键,无论该键有多深,如果未定义该键,则不会引发可能会损害程序流的错误。
JS双感叹号!!在这种情况下,符号可能会有所帮助。
const cars = {
petrol:{
price: 5000
},
gas:{
price:8000
}
}
假设我们有上面的对象,如果你试图用汽油价格记录汽车。
=> console.log(cars.petrol.price);
=> 5000
你肯定会从中得到5000英镑。但如果你想得到不存在的电动汽车,那么你将不受约束
=> console.log(cars.electric);
=> undefine
但使用!!这是将变量转换为布尔值(真或假)。
=> console.log(!!cars.electric);
=> false
一个快速而简单的解决方案是将您的对象转换为json,然后您就可以完成这个简单的任务:
const allowed = {
'/login' : '',
'/register': '',
'/resetpsw': ''
};
console.log('/login' in allowed); //returns true
如果使用数组,则对象键将转换为整数(例如0,1,2,3等),因此,它将始终为false
这些例子可以说明不同方式之间的差异。希望它能帮助您选择适合您需求的产品:
// 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"]