旧行李 2009-07-08 13:21 采纳率: 25%
浏览 242
已采纳

检查 JavaScript 对象中是否存在一个密钥?

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?

转载于:https://stackoverflow.com/questions/1098040/checking-if-a-key-exists-in-a-javascript-object

  • 写回答

18条回答 默认 最新

  • 七度&光 2009-07-08 15:51
    关注

    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"
    

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

    obj.hasOwnProperty("key") // true
    

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(17条)

报告相同问题?

悬赏问题

  • ¥15 像这种代码要怎么跑起来?
  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件