Checking if a key exists in a JavaScript object?

前端 未结 22 2261
礼貌的吻别
礼貌的吻别 2020-11-21 22:57

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

22条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-21 23:39

    If you are using underscore.js library then object/array operations become simple.

    In your case _.has method can be used. Example:

    yourArray = {age: "10"}
    
    _.has(yourArray, "age")
    

    returns true

    But,

    _.has(yourArray, "invalidKey")
    

    returns false

提交回复
热议问题