检查是否一个关键的JavaScript物件的存在? [英] Checking if a key exists in a JavaScript object?

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

问题描述

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

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

如果一个键不存在,我尝试访问它,它会返回false?或抛出一个错误?

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 };
obj["key"] != undefined // false, but the key exists!

您应该改为使用运营商:

You should instead use the in operator:

"key" in obj // true, regardless of the actual value

如果您要检查是否有键不存在,记得用括号:

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

!("key" in obj) // true if "key" doesn't exist in object
!"key" in obj   // ERROR!  Equivalent to "false in obj"

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

obj.hasOwnProperty("key") // true

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

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