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

标签 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,按钮)。

最佳答案

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/

相关文章:

javascript - 如何禁用模态上的 ESC 键?

javascript - 使用 JavaScript 从数组中删除零值

javascript - 为什么我的组件在没有严格模式的情况下渲染两次?

javascript - HTML 中的地址函数

javascript - 如何随机化(洗牌)Javascript Set

javascript - 将颜色从数组设置为多个元素

javascript - 如何将 Firebase 数据传递到函数中

javascript - 如何根据 Javascript 中的现有日期动态地将 Day 添加到 JSON 数组?

javascript - 提交表单数据时设置标题

javascript - 点击网页任意元素时触发js函数