检查 JavaScript 对象中是否存在键? [英] Checking if a key exists in a JavaScript object?

查看:32
本文介绍了检查 JavaScript 对象中是否存在键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

如果密钥不存在,而我尝试访问它,它会返回 false 吗?还是抛出错误?

解决方案

检查 undefined-ness 不是测试键是否存在的准确方法.如果键存在但值实际上是undefined怎么办?

var obj = { key: undefined };console.log(obj["key"] !== undefined);//false,但是key存在!

您应该改用 in 运算符:

var obj = { key: undefined };console.log(obj 中的key");//true,不管实际值

如果你想检查一个键是否不存在,记得使用括号:

var obj = { not_key: undefined };console.log(!("key" in obj));//如果对象中不存在key"则为真console.log(!"key" in obj);//不要这样做!相当于"false in obj"

或者,如果你想特别测试对象实例的属性(而不是继承的属性),使用hasOwnProperty:

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

对于inhasOwnProperty和key为undefined的方法之间的性能比较,请参见

How do I check if a particular key exists in a JavaScript object or array?

If a key doesn't exist, and I try to access it, will it return false? Or throw an error?

解决方案

Checking for undefined-ness is not an accurate way of testing whether a key exists. What if the key exists but the value is actually undefined?

var obj = { key: undefined };
console.log(obj["key"] !== undefined); // false, but the key exists!

You should instead use the in operator:

var obj = { key: undefined };
console.log("key" in obj); // true, regardless of the actual value

If you want to check if a key doesn't exist, remember to use parenthesis:

var obj = { not_key: undefined };
console.log(!("key" in obj)); // true if "key" doesn't exist in object
console.log(!"key" in obj);   // Do not do this! It is equivalent to "false in obj"

Or, if you want to particularly test for properties of the object instance (and not inherited properties), use hasOwnProperty:

var obj = { key: undefined };
console.log(obj.hasOwnProperty("key")); // true

For performance comparison between the methods that are in, hasOwnProperty and key is undefined, see this benchmark:

这篇关于检查 JavaScript 对象中是否存在键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆