Checking if a key exists in a JavaScript object?

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

    In 'array' world we can look on indexes as some kind of keys. What is surprising the in operator (which is good choice for object) also works with arrays. The returned value for non-existed key is undefined

    let arr = ["a","b","c"]; // we have indexes: 0,1,2
    delete arr[1];           // set 'empty' at index 1
    arr.pop();               // remove last item
    
    console.log(0 in arr,  arr[0]);
    console.log(1 in arr,  arr[1]);
    console.log(2 in arr,  arr[2]);

提交回复
热议问题