为什么空JavaScript数组在条件结构中的评估结果为true?
我在代码中遇到了很多错误,因为我期望这样的表达式:
I was encountering a lot of bugs in my code because I expected this expression:
Boolean([]);
评估为false.
但是情况并非如此,因为它评估为true.
But this wasn't the case as it evaluated to true.
因此,可能返回 []
的函数是这样的:
Therefore, functions that possibly returned []
like this:
// Where myCollection possibly returned [ obj1, obj2, obj3] or []
if(myCollection)
{
// ...
}else
{
// ...
}
没有做预期的事情.
我误以为 []
是一个空数组吗?
Am I mistaken in assuming that []
an empty array?
此外,此行为是否在所有浏览器中都一致?还是那里也有陷阱?顺便说一下,我在Goolgle Chrome中观察到了这种行为.
Also, Is this behavior consistent in all browsers? Or are there any gotchas there too? I observed this behavior in Goolgle Chrome by the way.
来自 http://www.sitepoint.com/javascript-truthy-falsy/
以下值始终是虚假的:
- false
- 0(零)
- "(空字符串)
- 空
- 未定义
- NaN (特殊的数字值,表示非数字!)
- false
- 0 (zero)
- "" (empty string)
- null
- undefined
- NaN (a special Number value meaning Not-a-Number!)
所有其他值都是真实的,包括"0"和"0".(引号为零),"false";(带引号的false),空函数,空数组和空对象.
All other values are truthy, including "0" (zero in quotes), "false" (false in quotes), empty functions, empty arrays, and empty objects.
关于为什么是这样的,我怀疑这是因为JavaScript数组只是特定类型的对象.专门处理数组将需要额外的开销来测试 Array.isArray()
.此外,在这种情况下,如果真数组的行为与其他类似数组的对象不同,则可能会造成混淆,而使所有类似数组的对象的行为相同甚至会更加昂贵.
Regarding why this is so, I suspect it's because JavaScript arrays are just a particular type of object. Treating arrays specially would require extra overhead to test Array.isArray()
. Also, it would probably be confusing if true arrays behaved differently from other array-like objects in this context, while making all array-like objects behave the same would be even more expensive.