【问题标题】:Javascript isNAN returns false if checking Object?如果检查对象,Javascript isNAN 返回 false?
【发布时间】:2014-02-28 20:16:13
【问题描述】:

我有一个行为异常的脚本。

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

当按钮是一个对象时,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, button)。

【问题讨论】:

标签: javascript


【解决方案1】:

IsNAN false // 应该是真的!

不一定。 :-) isNaN 仅在其参数为 NaN 时为真(如有必要,转换为 Number)。

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

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。)

【讨论】:

  • 哇!好回答!谢谢大家的。这似乎是最好的一个。不知道 isNaN 首先尝试将 value 转换为数字,然后检查它是否为 NaN。
【解决方案2】:

使用空对象调用的 isNaN() 预期为 false。

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

【讨论】:

    【解决方案3】:

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

    typeof(null) == 'object'

    isNaN(null) == 假

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-20
      • 2017-03-13
      • 2015-11-11
      • 1970-01-01
      • 2013-01-09
      • 1970-01-01
      相关资源
      最近更新 更多