سؤال

In JavaScript on Chrome and Firefox:

isNaN( "\n" ) gives false
parseFloat ( "\n" ) gives NaN

The same is yielded for \t, \r and \f.'

  • \n is a number
  • Parsed \n gives you Not A Number.
  • Escaped characters such as the NULL byte \0, \\ and \" do work as expected.
  • We know that NaN is a number, just not representable by any other value
  • So \n is a number, that's not representable.

Why do browsers implement it this way?

هل كانت مفيدة؟

المحلول

Because the toNumber conversion of any string that is comprised only of white space (or if it's empty) results in 0.

console.log(Number("\n")); // 0

The parseInt/Float methods actually require some numeric content to be converted, though it'll allow leading spaces, and trailing garbage.

console.log(parseFloat("   123.45odsifjj")); // 123.45

The toNumber conversion is defined in 9.3.1 ToNumber Applied to the String Type.

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

نصائح أخرى

This is due to the dynamic typing when you call isNaN. "\n" is not a NaN (a value specified for floats and doubles), "\n" is a string.

EDIT: Apparently, when calling isNaN("\n"), "\n" is converted to a number first using ToNumber which does not have exact same behavior as parseFloat.

However, W3C w3schools says for parseFloat:

If the first character cannot be converted to a number, parseFloat() returns NaN.

This is what causes the asymmetry.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top