为什么空的 JavaScript 数组在条件结构中评估为真? [英] Why do empty JavaScript arrays evaluate to true in conditional structures?

查看:34
本文介绍了为什么空的 JavaScript 数组在条件结构中评估为真?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的代码中遇到了很多错误,因为我期望这个表达式:

I was encountering a lot of bugs in my code because I expected this expression:

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
{
  // ...
}

没有做预期的事情.

我是否错误地假设 [] 是一个空数组?

Am I mistaken in assuming that [] an empty array?

此外,这种行为在所有浏览器中都一致吗?或者那里也有什么问题?顺便说一下,我在 Google 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/

以下值始终为假:

  • 0(零)
  • ""(空字符串)
  • 未定义
  • NaN(一个特殊的数值,表示非数字!)
  • false
  • 0 (zero)
  • "" (empty string)
  • null
  • undefined
  • NaN (a special Number value meaning Not-a-Number!)

所有其他值都是真值,包括 "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.

这篇关于为什么空的 JavaScript 数组在条件结构中评估为真?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆