Why is `'\t\n ' == false` in JavaScript?

巧了我就是萌 提交于 2019-12-23 10:44:11

问题


In JavaScript...

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

I can assume that any string that consists solely of whitespace characters is considered equal to false in JavaScript.

According to this article, I figured that false would be converted to 0, but was unable to find mention of whitespace considered equal to false using Google.

Why is this? Is there some good reading on the subject besides digging into the ECMAScript spec?


回答1:


This page provides a good summary of the rules.

Going by those rules, the '\t\n ' is converted in a number (Number('\t\n') ==> 0), and the false is converted into a number (Number(false) ==> 0), and hence the two are equal.


Alex's answer is also a good breakdown of the particular case of '\t\n ' == false.


An important distinction is that '\t\n ' is not falsy. For example:

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



回答2:


whitespace == false; // true

Type coercion, love it or hate it.

Digging into the ES5 spec atm. There really isn't any other good way apart from reading what someone else dug out of the ES5 spec.

If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.

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

Booleans get converted to 0 or 1. The reason this is the case is that whitespace == 0

And if you really want to know about new Number(" ") then read this 9.3.1 in the ES5 spec.

The important line is :

The MV of StringNumericLiteral ::: StrWhiteSpace is 0.




回答3:


Here is how I think it works, based on my readings and Raynos' answer (as well as the other latecomers to the party).

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

Please let me know if I have something wrong.




回答4:


I think the process can be described in a recursive function. (Imagining we live in a world where JavaScript only has the strict equality operator.)

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

A StringNumericLiteral that is empty or contains only white space is converted to +0.



来源:https://stackoverflow.com/questions/5634372/why-is-t-n-false-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!