简体   繁体   中英

Why does an empty array pass the if(array !== []) check

Hi I've been debugging a javascript issue where an empty array default value set in state, passes a conditional check which checks if it is empty.

I must be overlooking something. Here is what I have:

state = {
  array: []
};

if(array !== []){
  //do something
}

I also have a check for if it is empty - although I need to extend it so that this [] array doesn't return true.

I have also tried array.length > 0 in lieu of checking against [].

Any ideas please?

Thanks

They are not equal because a new array is used in check and it points to the new spot in memory.

So, these are just two empty arrays, but they do not point to the same spot in the memory (as array is not a primitive type). That is why they are not equal.

Here you can find a few valid ways to check that: https://www.geeksforgeeks.org/check-if-an-array-is-empty-or-not-in-javascript/#:~:text=the%20array%20exists.-,The%20array%20can%20be%20checked%20if%20it%20is%20empty%20by,the%20array%20is%20not%20empty .

You want to do the check for undefined first. If you do it the other way round, it will generate an error if the array is undefined.

if (array === undefined || array.length == 0) {
    // array empty or does not exist
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM