hurriedly% 2009-07-08 13:21 采纳率: 100%
浏览 305
已采纳

检查 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

  • 写回答

19条回答 默认 最新

  • perhaps? 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

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

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog