javascript - 空数组是否总是被解释为 TRUE?

标签 javascript arrays truthiness

所有浏览器版本都是这种情况吗?意思是,空数组始终被视为 TRUE 而绝不会像 bool 表示那样被视为 FALSE?

var x = [];

if(x)
   alert('this could be an empty array');
else
    alert('this could NEVER be an empty array');

最佳答案

根据 ECMA Script 5.1 specification's Boolean expression evaluation function ,任何对象将始终被评估为 Truthy。因此,数组将始终被评估为真实。

+-----------------------------------------------------------------------+
| Argument Type | Result                                                |
|:--------------|------------------------------------------------------:|
| Undefined     | false                                                 |
|---------------|-------------------------------------------------------|
| Null          | false                                                 |
|---------------|-------------------------------------------------------|
| Boolean       | The result equals the input argument (no conversion). |
|---------------|-------------------------------------------------------|
| Number        | The result is false if the argument is +0, −0, or NaN;|
|               | otherwise the result is true.                         |
|---------------|-------------------------------------------------------|
| String        | The result is false if the argument is the empty      |
|               | String (its length is zero); otherwise the result is  |
|               | true.                                                 |
|---------------|-------------------------------------------------------|
| Object        | true                                                  |
+-----------------------------------------------------------------------+

根据最后一行,对于任何对象,结果将为 true

引用:My answer SO中的另一个问题

关于javascript - 空数组是否总是被解释为 TRUE?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22962411/

相关文章:

javascript - 输入和输出区域之间的行高不同

ios - Objective-c Json 解析空数组错误或 Bug?

python - 为什么 NotImplemented 在 Python 3 中是真实的?

javascript - 实现 isNil

javascript - curl机制,在expressjs代码里面

javascript - 当我向下滚动页面时,如何让一个 div 跟随我?

javascript - GDPR : youtube-nocookie embedded URL's, 需要访问者的许可吗?

php - 对 mysql_fetch_array 内的数组进行排序

c++ - 在常数时间内提取子 vector

javascript - TypeScript 中以下条件有什么区别?