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

查看:58
本文介绍了为什么空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.

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

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