旧行李 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 禁止修改windows系统时间
  • ¥50 kinect连接win11笔电导致音视频设备消失
  • ¥15 python线性查找题
  • ¥20 GDB info thread 显示格式问题
  • ¥15 WiFi串口通信问题
  • ¥15 基于python建立整数线性规划问题并求解
  • ¥30 Semantic Kernel + OllamaSharp 集成本地大语言模型
  • ¥15 channels运行加载异常
  • ¥15 用C语言实现语音的读取及播放