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

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


当前回答

const rawObject = {};
rawObject.propertyKey = 'somethingValue';

console.log(rawObject.hasOwnProperty('somethingValue'));
// expected output: true

检查给定对象中存在的特定键,hasOwnProperty将在此处工作。

其他回答

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

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

参考:

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

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

检查未定义性不是测试密钥是否存在的准确方法。如果键存在但值实际上未定义怎么办?

var obj={key:undefined};console.log(obj[“key”]!==未定义);//false,但密钥存在!

您应该改用in运算符:

var obj={key:undefined};console.log(obj中的“key”);//true,无论实际值如何

如果要检查键是否不存在,请记住使用括号:

var obj={not_key:undefined};console.log(!(obj中的“key”));//如果对象中不存在“key”,则为trueconsole.log(obj中的!“key”);//不要这样做!它相当于“obj中的false”

或者,如果要特别测试对象实例的财产(而不是继承的财产),请使用hasOwnProperty:

var obj={key:undefined};console.log(obj.hasOwnProperty(“key”));//真的

有关hasOwnProperty和key未定义的方法之间的性能比较,请参阅以下基准:

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 Destructuring的新解决方案:

let obj = {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3",
};

let {key1, key2, key3, key4} = obj;

// key1 = "value1"
// key2 = "value2"
// key3 = "value3"
// key4 = undefined

// Can easily use `if` here on key4
if(!key4) { console.log("key not present"); } // Key not present

检查JavaScript Destructuring的其他用法