5

如何在NaN不使用该isNaN功能的情况下检查输入值是否?

4

2 回答 2

8

如果你可以使用ECMAScript 6,你有Object.is

return Object.is(obj, NaN);

否则,这是一个选项,来自underscore.js的源代码:

// Is the given value `NaN`?
_.isNaN = function(obj) {
  // `NaN` is the only value for which `===` is not reflexive.
  return obj !== obj;
};

还有他们对该功能的说明:

注意:这与原生 isNaN 函数不同,如果变量未定义,它也会返回 true。

于 2012-04-10T19:00:48.730 回答
1

将输入转换为数字,并检查减法是否不为零:

var x = 'value';
var is_NaN = +x - x !== 0; // The + is actually not needed, but added to show
                           // that a number conversion is made.
于 2012-04-10T19:02:39.520 回答