我有一个行为奇怪的脚本。
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,按钮)。
最佳答案
IsNAN false // should be true!
不一定。 :-) isNaN
仅当其参数(必要时转换为 Number
)为 NaN
时才为 true。
根据对象是什么,转换为 Number
时,它可能是也可能不是 NaN
。这取决于对象转换为其原始值时会发生什么。例如,null
会转换为 0
。在许多其他情况下,转换为基元涉及将其转换为字符串(例如数组),并且某些对象的默认 toString
可能会返回可以转换为非 的内容NaN
数字
。
非 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
。)
关于如果检查 Object? Javascript isNAN 返回 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22094752/