如何检查JavaScript对象或数组中是否存在特定键?
如果密钥不存在,并且我试图访问它,它会返回false吗?或者抛出错误?
如何检查JavaScript对象或数组中是否存在特定键?
如果密钥不存在,并且我试图访问它,它会返回false吗?或者抛出错误?
当前回答
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
其他回答
接受的答案指的是对象。小心使用Array上的in运算符查找数据而不是键:
("true" in ["true", "false"])
// -> false (Because the keys of the above Array are actually 0 and 1)
测试数组中的现有元素:查找项目是否在JavaScript数组中的最佳方法?
可选链接运算符:
常量发票={客户:{地址:{城市:“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>
这将有效地检查是否定义了该键,无论该键有多深,如果未定义该键,则不会引发可能会损害程序流的错误。
要查找对象中是否存在键,请使用
对象.keys(obj).includes(key)
ES7包括检查数组是否包含项的方法,这是indexOf的一种更简单的替代方法。
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"]