How to tell whether value is NaN without using isNaN, which has false positives? [duplicate]

荒凉一梦 提交于 2019-11-29 14:39:14

If you can use ECMAScript 6, you have Object.is:

return Object.is(obj, NaN);

Otherwise, here is one option, from the source code of underscore.js:

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

Also their note for that function:

Note: this is not the same as the native isNaN function, which will also return true if the variable is undefined.

Rob W

Convert the input to a number, and check whether the substraction is not zero:

var x = 'value';
var is_NaN = +x - x !== 0; // The + is actually not needed, but added to show
                           // that a number conversion is made.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!