如何检查JavaScript对象或数组中是否存在特定键?
如果密钥不存在,并且我试图访问它,它会返回false吗?或者抛出错误?
如何检查JavaScript对象或数组中是否存在特定键?
如果密钥不存在,并且我试图访问它,它会返回false吗?或者抛出错误?
当前回答
它将返回undefined。
var aa={hello:“world”};警报(aa[“hello”]);//带有“world”的弹出框警报(aa[“再见”]);//带有“未定义”的弹出框
undefined是一个特殊的常量值。所以你可以说,例如。
// note the three equal signs so that null won't be equal to undefined
if( aa["goodbye"] === undefined ) {
// do something
}
这可能是检查丢失钥匙的最佳方法。然而,正如下面的评论所指出的,理论上,您可能希望未定义实际值。我从来都不需要这样做,也无法马上想到我想要这样做的原因,但为了完整起见,您可以使用in运算符
// this works even if you have {"goodbye": undefined}
if( "goodbye" in aa ) {
// do something
}
其他回答
这些例子可以说明不同方式之间的差异。希望它能帮助您选择适合您需求的产品:
// 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"]
"key" in obj
可能只测试与数组键非常不同的对象属性值
使用“反射”的替代方法
根据MDN
Reflect是一个内置对象,它提供可拦截的方法JavaScript操作。静态Reflect.has()方法的工作方式类似于in运算符作用
变量obj={a: 未定义,b: 1中,c: “hello world”}console.log(Reflect.has(obj,“a”))console.log(Reflect.has(obj,'b'))console.log(Reflect.has(obj,“c”))console.log(Reflect.has(obj,“d”))
我应该使用它吗?
这取决于。
Reflect.has()比公认答案中提到的其他方法慢(根据我的基准测试)。但是,如果您只在代码中使用它几次,我看不出这种方法有多大问题。
const object1 = {
a: 'something',
b: 'something',
c: 'something'
};
const key = 's';
// Object.keys(object1) will return array of the object keys ['a', 'b', 'c']
Object.keys(object1).indexOf(key) === -1 ? 'the key is not there' : 'yep the key is exist';
检查javascript对象中是否存在属性的三种方法:
!!对象.属性将值转换为布尔值。对于除false值之外的所有值返回true对象中的“属性”如果属性存在,无论其值如何(甚至为空),都将返回trueobj.hasOwnProperty(“属性”)不检查原型链。(由于所有对象都有toString方法,因此1和2将返回true,而3可以返回false。)
参考:
http://book.mixu.net/node/ch5.html