北城已荒凉 2009-07-08 13:21 采纳率: 0%
浏览 155
已采纳

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

  • 写回答

16条回答 默认 最新

  • 笑故挽风 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

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

报告相同问题?

悬赏问题

  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥15 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)