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

In JavaScript ...

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

I can assume that any line consisting solely of whitespace is considered equal falsein JavaScript.

According to this article, I realized that I falsewould be converted to 0, but could not find the mention of missing spaces equal falsewith Google.

Why is this? Are there any good readings on this subject, besides the fact that you delve into the ECMAScript specification?

+5
source share
4 answers

This page gives a good summary of the rules.

, '\t\n ' (Number('\t\n') ==> 0), false (Number(false) ==> 0), , , .


Alex '\t\n ' == false.


, '\t\n ' . :

if ('\t\n ') alert('not falsy'); // will produce the alert
+3
whitespace == false; // true

, .

ES5. , , - ES5.

Type (x) , ToNumber (x) == y.

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

0 1. , whitespace == 0

new Number(" "), 9.3.1 ES5.

:

MV StringNumericLiteral: StrWhiteSpace 0.

+2

, , Raynos ( ).

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

, , - .

+1

, . (, , JavaScript .)

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

StringNumericLiteral, , +0.

+1

All Articles