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条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度