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

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


当前回答

ES6溶液

使用Array#some和Object.keys。如果给定的键存在于对象中,则返回true,否则返回false。

var obj={foo:'one',bar:'two'};函数isKeyInObject(obj,key){var res=对象.keys(obj).some(v=>v==key);console.log(res);}isKeyInObject(obj,'foo');isKeyInObject(obj,“something”);

单行示例。

console.log(Object.keys({foo:'one',bar:'two'}).some(v=>v=='foo'));

其他回答

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

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

虽然这不一定检查键是否存在,但它确实检查值的真实性。其中未定义和空值属于。

布尔(obj.foo)

这个解决方案最适合我,因为我使用了typescript,并且在obj或obj.hasOwnProperty('fo')中使用了像so'foo'这样的字符串检查密钥是否存在并不能为我提供智能感知。

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';

如果您使用的是underscore.js库,那么对象/数组操作就变得简单了。

在您的情况下,可以使用_.has方法。例子:

yourArray = {age: "10"}

_.has(yourArray, "age")

返回true

But,

_.has(yourArray, "invalidKey")

返回false

检查javascript对象中是否存在属性的三种方法:

!!对象.属性将值转换为布尔值。对于除false值之外的所有值返回true对象中的“属性”如果属性存在,无论其值如何(甚至为空),都将返回trueobj.hasOwnProperty(“属性”)不检查原型链。(由于所有对象都有toString方法,因此1和2将返回true,而3可以返回false。)

参考:

http://book.mixu.net/node/ch5.html