search

Home  >  Q&A  >  body text

javascript - js 中的 isNaN([1]) 为什么返回false

传入长度为1的数组时

isNaN([1]);    //false

但是

isNaN([1,2]);    //true

还有

NaN === NaN  //false

好神奇啊。

阿神阿神2901 days ago692

reply all(6)I'll reply

  • PHP中文网

    PHP中文网2017-04-10 14:48:32

    NaN !== NaN 是可以理解的,毕竟 4 / 'error' 也不该等于 5 / 'error'

    isNaN([1])false,是因为 isNaN 接受的是数字类型,于是 [1] 被自动转换为了数字类型再传递给 isNaN,而转换结果是 1。不信你可以看到 Number([1]) 是 1。

    而你可以看到 Number([1,2]) 的结果是 NaN,于是 isNaN([1,2]) 自然是 true 了。

    reply
    0
  • 阿神

    阿神2017-04-10 14:48:32

    http://es5.github.io/#x15.1.2.4

    扫一眼规范,就三行文字,一目了然。

    15.1.2.4 isNaN (number) # Ⓣ Ⓡ Ⓖ

    Returns true if the argument coerces to NaN, and otherwise returns false.

    • If ToNumber(number) is NaN, return true.
    • Otherwise, return false.

    NOTE A reliable way for ECMAScript code to test if a value Xis a NaN is an expression of the form X !== X. The result will be true if and only if X is a NaN.

    reply
    0
  • 迷茫

    迷茫2017-04-10 14:48:32

    上边都说得差不多了,就是数组转换成数字的问题。一般对象转换成数字先调用valueOf方法,如果有这个方法并且返回值就用它。没有的话就调用toString方法。数组的valueOf返回数组本身,所以会调用toString。空数组toString是””,空串转数字是0。[1].toString是”1”,转数字是1。[1,2].toString是”1,2”,这个字符串转换成数字是NaN.

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-10 14:48:32

    http://yanhaijing.com/es5/#256

    reply
    0
  • ringa_lee

    ringa_lee2017-04-10 14:48:32

    [1](1个数字元素),转换成字符串为"1",因为类型转换所以数字是9.所以isNaN就是false了。
    [1,2](一个数组),类型转换成数字就是NaN了!

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-10 14:48:32

    结合楼上说的,看图吧。

    reply
    0
  • Cancelreply