Boolean('')为false和Boolean(new String(''))有什么区别?

时间:2018-10-25 12:45:23

标签: javascript boolean-expression

我怀疑两者都是字符串,为什么获取不同的布尔值 Boolean('')为false和 Boolean(new String('')) ?

2 个答案:

答案 0 :(得分:3)

Boolean函数为所有对象引用返回truenew String("")创建一个字符串 object 。相反,""只是一个字符串基元。 Boolean返回false以获得空白字符串基元。

当作为函数(而不是构造函数)调用时,Boolean返回规范的ToBoolean abstract operation的结果:

抽象操作ToBoolean根据表9将参数转换为Boolean类型的值:
+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+
|                 Table 9: ToBoolean Conversions                  |
+−−−−−−−−−−−−−−−+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+
| Argument Type | Result                                          |
+−−−−−−−−−−−−−−−+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+
| Undefined     | Return false.                                   |
+−−−−−−−−−−−−−−−+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+
| Null          | Return false.                                   |
+−−−−−−−−−−−−−−−+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+
| Boolean       | Return argument.                                |
+−−−−−−−−−−−−−−−+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+
| Number        | If argument is +0, −0, or NaN, return false;    |
|               | otherwise return true.                          |
+−−−−−−−−−−−−−−−+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+
| String        | If argument is the empty String (its length is  |
|               | zero), return false; otherwise return true.     |
+−−−−−−−−−−−−−−−+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+
| Symbol        | Return true.                                    |
+−−−−−−−−−−−−−−−+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+
| Object        | Return true.                                    |
+−−−−−−−−−−−−−−−+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+

从表的最后一行可以看到,任何对象对象都将产生true

答案 1 :(得分:0)

  1. 以下值被强制为false,因为它们是falsy值:''NaNundefinednull,{{1 }}。
  2. 所有其他内容都将被强制使用0,因为它们是true值。

您要使用的功能:

truthy

并包含以下内容:

Boolean('') // Coercing a primitive empty string (falsy).