如果检查Object,Javascript isNAN返回false?

时间:2014-02-28 12:05:57

标签: javascript

我有一个行为奇怪的脚本。

console.log (typeof button);
console.log ('IsNAN ' + isNaN(button));
console.log ('isNumeric ' + jQuery.isNumeric(button));
console.log ();

当button是一个对象时,isNaN应该返回true;因为对象是NaN。然而,控制台显示不同:

object
IsNAN false // should be true!
isNumeric false

为什么?

编辑:有问题的脚本是http://flesler-plugins.googlecode.com/files/jquery.serialScroll-1.2.2.js

第126行@函数跳转(e,按钮)。

3 个答案:

答案 0 :(得分:3)

  

IsNAN是假的//应该是真的!

不一定。 :-) isNaN只有在它的参数(如有必要时转换为Number)为NaN时才为真。

根据对象的内容,转换为NaN时,它可能是Number,也可能不是null。它取决于将对象转换为其原始值时发生的情况。例如,0会转换为toString。在许多其他情况下转换为原语涉及将其转换为字符串(例如,数组),并且某些对象的默认NaN可能返回可以转换为非Number {的内容。 {1}}。

NaN个对象的示例:

// null
console.log(Number(null));          // 0

// an array (which becomes "23" when converted to primitive, because
// arrays do `join` for `toString`; then the "23" becomes 23)
console.log(Number([23]));          // 23

// another object implementing toString or valueOf in a way that returns
// something convertable to a non-NaN number
console.log(Number(new Foo("47"))); // 47

...其中Foo是:

function Foo(value) {
    this.value = value;
}
Foo.prototype.toString = function() {
    return this.value;
};

(在上文中,toString也可以是valueOf。)

答案 1 :(得分:2)

使用null对象调用的isNaN()应该是false。

如果您的对象不为null且无法转换为数字,则它将返回true。

答案 2 :(得分:0)

我认为你的变量按钮等于null。

typeof(null)==' object'

isNaN(null)== false

相关问题