JavaScript的:空数组,[]的值为true在条件结构。为什么是这样? [英] JavaScript: empty array, [ ] evaluates to true in conditional structures. Why is this?

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

问题描述

我遇到了很多虫子在我的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屋!

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