Checking if a key exists in a JavaScript object?

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

    a fast and easy solution is to convert your object to json then you will be able to do this easy task

        const allowed = {
            '/login' : '',
            '/register': '',
            '/resetpsw': ''
        };
        console.log('/login' in allowed); //returns true
    

    if you use an array the object key will be converted to integers ex 0,1,2,3 etc, therefore, it will always be false

提交回复
热议问题