有效的错误值

时间:2014-04-29 14:49:05

标签: javascript boolean

将任何值转换为Boolean都会返回falsetrue。例如:

> Boolean (false)
false
> Boolean (null)
false
> Boolean (undefined)
false
> Boolean ("")
false

但是0很特别,因为它是一个数字。我认为这是一个有效的假值:

> Boolean (0)
false

是否还有其他有效的错误值?

1 个答案:

答案 0 :(得分:14)

根据ECMA 5.1 Standards,表达式的真实性将根据下表确定

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

所以,您错过了-0NaN

console.log(Boolean(-0));
# false
console.log(Boolean(NaN));
# false