Checking if a key exists in a JavaScript object?

前端 未结 22 2639
礼貌的吻别
礼貌的吻别 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:28

    Answer:

    if ("key" in myObj)
    {
        console.log("key exists!");
    }
    else
    {
        console.log("key doesn't exist!");
    }
    

    Explanation:

    The in operator will check if the key exists in the object. If you checked if the value was undefined: if (myObj["key"] === 'undefined'), you could run into problems because a key could possibly exist in your object with the undefined value.

    For that reason, it is much better practice to first use the in operator and then compare the value that is inside the key once you already know it exists.

提交回复
热议问题