JavaScript:空数组,[ ] 在条件结构中计算为真。为什么是这样?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19146176/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript: empty array, [ ] evaluates to true in conditional structures. Why is this?
提问by racl101
I was encountering a lot of bugs in my code because I expected this expression:
我在我的代码中遇到了很多错误,因为我期望这个表达式:
Boolean([]);
to evaluate to false.
Boolean([]);
评估为假。
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.
没有做预期的事情。
Am I mistaken in assuming that []
an empty array?
我假设[]
一个空数组是错误的吗?
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.
另外,这种行为在所有浏览器中是否一致?或者那里也有什么问题?顺便说一下,我在 Google Chrome 中观察到了这种行为。
回答by Barmar
From http://www.sitepoint.com/javascript-truthy-falsy/
来自http://www.sitepoint.com/javascript-truthy-falsy/
The following values are always falsy:
以下值始终为假:
- false
- 0 (zero)
- "" (empty string)
- null
- undefined
- NaN(a special Number value meaning Not-a-Number!)
- 错误的
- 0(零)
- ""(空字符串)
- 空值
- 不明确的
- NaN(一个特殊的数值,表示非数值!)
All other values are truthy, including "0" (zero in quotes), "false" (false in quotes), empty functions, empty arrays, and empty objects.
所有其他值都是真值,包括“0”(引号中为零)、“false”(引号中为 false)、空函数、空数组和空对象。
回答by DevlshOne
You should be checking the .length
of that array to see if it contains any elements.
您应该检查该.length
数组的 以查看它是否包含任何元素。
if (myCollection) // always true
if (myCollection.length) // always true when array has elements
if (myCollection.length === 0) // same as is_empty(myCollection)