简体   繁体   English

为什么空数组通过 if(array !== []) 检查

[英]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.嗨,我一直在调试 javascript 问题,其中在 state 中设置的空数组默认值通过了条件检查,检查它是否为空。

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.我还检查了它是否为空 - 尽管我需要扩展它以便这个 [] 数组不返回 true。

I have also tried array.length > 0 in lieu of checking against [].我还尝试使用 array.length > 0 来代替检查 []。

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.它们不相等,因为在检查中使用了一个新数组,它指向 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).因此,这些只是两个空的 arrays,但它们并不指向 memory 中的同一个位置(因为数组不是原始类型)。 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 .在这里您可以找到一些有效的方法来检查: https://www.geeksforgeeks.org/check-if-an-array-is-empty-or-not-in-javascript/#:~:text=the% 20array%20exists.-,%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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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