2

所有浏览器版本都是这种情况吗?意思是,一个空数组总是被认为是 TRUE 而不是 FALSE 作为布尔表示?

var x = [];

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

5 回答 5

3

根据ECMA Script 5.1 规范的布尔表达式评估函数,任何对象都将始终被评估为真值。因此,数组将始终被评估为真实。

+-----------------------------------------------------------------------+
| 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.

参考:对 SO 中另一个问题的回答

于 2014-04-09T12:25:53.133 回答
1

数组是真实的,是的。如果您想要一种简单的方法来检查是否为空,请使用以下length属性:

var x = [];

if(x.length)
    alert('this array is not empty');
于 2014-04-09T12:25:31.070 回答
0

是的。所有对象都是真实的。总是。

于 2014-04-09T12:23:39.137 回答
0

是的。数组是一个对象。所以这是真的。而 null/undefined 为 false

于 2014-04-09T12:24:45.177 回答
0

默认情况下,这些东西在 javascript 中被视为 false。

  1. 错误的
  2. 无效的
  3. 不明确的
  4. '' 或 "" [空字符串]
  5. 0 [零]
于 2014-04-09T12:26:45.380 回答