【问题标题】:Why is `'\t\n ' == false` in JavaScript?为什么 `'\t\n ' == false` 在 JavaScript 中?
【发布时间】:2011-08-03 19:28:25
【问题描述】:

在 JavaScript 中...

'\t\n ' == false // true

我可以假设任何仅由空白字符组成的字符串在 JavaScript 中都被视为等于 false

According to this article,我认为false 将转换为0,但无法使用谷歌找到与false 相等的空格。

这是为什么?除了深入研究 ECMAScript 规范之外,还有其他关于该主题的好读物吗?

【问题讨论】:

    标签: javascript type-coercion


    【解决方案1】:

    This page 很好地总结了规则。

    按照这些规则,'\t\n ' 转换为数字 (Number('\t\n') ==> 0),false 转换为数字 (Number(false) ==> 0),因此两者相等。


    Alex's answer 也是对'\t\n ' == false 特例的一个很好的细分。


    一个重要的区别是'\t\n ' 不是虚假的。例如:

    if ('\t\n ') alert('not falsy'); // will produce the alert
    

    【讨论】:

    • 感谢您的回答,我在my answer 中采取的步骤正确吗?
    • @alex,这也是我的理解。另请注意,'\t\n ' 不是虚假的(没有相等运算符,因此没有类型转换),正如我在答案中添加的那样。
    • 谢谢,我不应该在我的问题中写这个,因为这不是我的意思。我已经更新了我的问题。再次感谢您的回答。
    • @alex ;) 另外,如果您有兴趣,可以非常详细地了解 object 转换会发生什么:article by Ben Cherry.
    【解决方案2】:
    whitespace == false; // true
    

    类型强制,爱它或恨它。

    深入研究 ES5 规范。除了阅读其他人从 ES5 规范中挖掘出来的内容之外,真的没有其他好的方法。

    如果 Type(x) 是 Boolean,则返回比较结果 ToNumber(x) == y。

    new Number(false) == " "; // true

    布尔值被转换为 0 或 1。出现这种情况的原因是 whitespace == 0

    如果您真的想了解 new Number(" "),请阅读 ES5 规范中的 9.3.1。

    重要的一行是:

    StringNumericLiteral ::: StrWhiteSpace 的 MV 为 0。

    【讨论】:

    • @Alex new Number(" ") 创建 0。" StringNumericLiteral ::: StrWhiteSpace 的 MV 为 0。"
    【解决方案3】:

    根据我的阅读和Raynos' answer(以及派对的其他迟到者),这是我认为它的工作原理。

    // Original expression
    lg('\t\n ' == false);
    // Boolean false is converted to Number
    lg('\t\n ' == new Number(false));
    // Boolean has been converted to 0
    lg('\t\n ' == 0);
    // Because right hand operand is 0, convert left hand to Number
    lg(new Number('\t\n ') == 0);
    // Number of whitespace is 0, and 0 == 0
    lg(0 == 0);
    

    jsFiddle.

    如果我有什么问题请告诉我。

    【讨论】:

      【解决方案4】:

      我认为这个过程可以用递归函数来描述。 (想象我们生活在一个 JavaScript 只有严格相等运算符的世界。)

      function equals(x, y) {
          if (typeof y === "boolean") {
              return equals(x, +y);
          }
          else if (typeof x === "string") {
              return +x === y;
          }
      }
      

      为空或仅包含空格的 StringNumericLiteral 将转换为 +0。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-03-19
        • 1970-01-01
        • 2015-05-09
        • 1970-01-01
        • 1970-01-01
        • 2017-01-16
        • 1970-01-01
        相关资源
        最近更新 更多