JavaScript的:空数组,[]的值为true在条件结构。为什么是这样? [英] JavaScript: empty array, [ ] evaluates to true in conditional structures. Why is this?
问题描述
我遇到了很多虫子在我的code,因为我预计今年前pression:
I was encountering a lot of bugs in my code because I expected this expression:
布尔([]);
评估为false。
Boolean([]);
to evaluate to 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
{
// ...
}
没做的事情预期。
did not do expected things.
是我错在假设 []
空数组?
此外,这种行为在所有的浏览器是否一致?还是有什么陷阱有太多?我的方式观察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.
推荐答案
从<一个href=\"http://www.sitepoint.com/javascript-truthy-falsy/\">http://www.sitepoint.com/javascript-truthy-falsy/
下面的值总是falsy:
The following values are always falsy:
- 假
- 0(零)
- (空字符串)
- 空
- 未定义
- NAN(一种特殊的数字值,这意味着不能非数字!)
所有其他值都truthy,包括(以引号零)0,假(加引号假),空函数,空数组和空对象。
All other values are truthy, including "0" (zero in quotes), "false" (false in quotes), empty functions, empty arrays, and empty objects.
这篇关于JavaScript的:空数组,[]的值为true在条件结构。为什么是这样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!