What is "" in JavaScript in fact?

This says falsewhat means ""- number:

alert(isNaN("")); 

This says NaNthat means it is ""not a number and cannot be converted:

alert(parseFloat(""));

I expected the second code to convert ""to 0, since it ""is a number when testing in IsNaN, but I was wrong! Am I crazy or just missed something?

+5
source share
5 answers

parseFloattries to parse a number from a string where it isNaN converts an argument to a number before checking it:

Number("") //0 http://ecma-international.org/ecma-262/5.1/#sec-9.3.1
parseFloat("") //NaN http://ecma-international.org/ecma-262/5.1/#sec-15.1.2.3

This seems to be “broken” or “confusing,” so from the specs:

ECMAScript, , X NaN, X! == X. , X NaN.

0 !== 0 // false
NaN !== NaN //true

function isExactlyNaN(x) {
    return x !== x;
}
+3

isNaN Number , NaN.

, , 0 (+"" === 0), 0 NaN, false.

parseFloat NaN (parseFloat("") === NaN).

+1

NaN . , NaN.

-, NaN JS.

+1

Javascript 0, isNaN. parseFloat, , NaN..

0

, .

isNaN , , false, , Number(value) .

parseFloat , - , NaN, .

Programmers tend to over-use parseIntand parseFloatto enforce, when in most cases they should use Numberthat is more rigorous and is not confused.

0
source

All Articles