【问题标题】:Why Not a Number (NaN) is a Number in Javascript? [duplicate]为什么不是数字(NaN)是 Javascript 中的数字? [复制]
【发布时间】:2014-10-03 12:16:48
【问题描述】:

假设我想转换一个显然不是数字的字符串,但最终我得到一个数字!?

var b = parseFloat("a");

console.log(b); // output NaN

console.log(typeof b); // print number!

这里到底发生了什么? NaN 表示不是数字,对吧?

好的,所以 NaN == NaN 总是错误的。但是:

typeof 1/0 // prints NaN
1/0 == 1/0 // its true

【问题讨论】:

  • typeof null === 'object'的情况与typeof NaN === 'number'相同。
  • 关于您的编辑,typeof 1/0 被评估为(typeof 1)/0,即"number"/0。 JS 会尝试将字符串转换为数字,这会导致NaN,所以你正在做NaN/0,这当然会导致NaN。即使不知道运算符的存在,很明显typeof 1 是首先执行的,因为 a) typeof 总是返回一个字符串,NaN 不是字符串,b) NaN 是一个值,而不是一个类型, c) typeof从不返回NaN1/0 返回无穷大。

标签: javascript


【解决方案1】:
var b = parseFloat("a");

console.log(b); // output NaN

console.log(typeof b);  // number! what else would it be?
console.log(!isNaN(b)); // false 
console.log(isNaN(b));  // true!

console.log(isNaN('stringoftext'));  // true! this is not good, that's REALLY not a number
//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN

console.log(typeof b === 'number' && isNaN(b) === true); // It is NOT A NUMBER

console.log(b != b); // true , means that it is NaN
//http://stackoverflow.com/a/14220688/3741423

【讨论】:

  • console.log(b == b) ???错误的!?你能解释一下这种行为吗?
  • @Borachio:NaN 是一个不等于任何东西的特殊值。甚至不是它自己:NaN == NaN 是假的。
  • 我发布了另一个讨论它的线程stackoverflow.com/a/14220688/3741423我也修复了,这是真的不是假的,谢谢slebetman
  • 我也喜欢这个人的解释:stackoverflow.com/a/23666623/3741423
  • a = 'a'; console.log(typeof a);// == string console.log(a / 2); // == NaN console.log(typeof a/2); // == NaN console.log(typeof (a/2));// == Number
【解决方案2】:

它并不是真正特定于 Javascript。它与计算机科学更相关。

在计算中,NaN,代表非数字,是数值数据类型值,表示未定义或无法表示的值,尤其是在浮点计算中。

可以返回NaN的操作有3种

Operations with a NaN as at least one operand.
Indeterminate forms
    The divisions 0/0 and ±∞/±∞
    The multiplications 0×±∞ and ±∞×0
    The additions ∞ + (−∞), (−∞) + ∞ and equivalent subtractions
    The standard has alternative functions for powers:
        The standard pow function and the integer exponent pown function define 00, 1∞, and ∞0 as 1.
        The powr function defines all three indeterminate forms as invalid operations and so returns NaN.

Real operations with complex results, for example:
    The square root of a negative number.
    The logarithm of a negative number
    The inverse sine or cosine of a number that is less than −1 or greater than +1.

【讨论】:

    【解决方案3】:

    没有你想看到的解释。 Funciton parseFloat 可能会引发异常,但这是另一种方法。 它返回称为“非数字”的特殊“数字”。 只是不要以这个名字循环。

    【讨论】:

      猜你喜欢
      • 2013-05-27
      • 2015-01-14
      • 2018-07-15
      • 2013-11-17
      • 2013-11-26
      • 2018-08-09
      • 1970-01-01
      相关资源
      最近更新 更多