ESLint 意外使用 isNaN

ESLint Unexpected use of isNaN

我正在尝试在 Node.js 模块中的箭头函数中使用 isNaN 全局函数,但出现此错误:

[eslint] Unexpected use of 'isNaN'. (no-restricted-globals)

这是我的代码:

const isNumber = value => !isNaN(parseFloat(value));

module.exports = {
  isNumber,
};

知道我做错了什么吗?

PS:我正在使用爱彼迎风格指南。

作为 documentation suggests, use Number.isNaN.

const isNumber = value => !Number.isNaN(Number(value));

引用 Airbnb 的文档:

Why? The global isNaN coerces non-numbers to numbers, returning true for anything that coerces to NaN. If this behavior is desired, make it explicit.

// bad
isNaN('1.2'); // false
isNaN('1.2.3'); // true

// good
Number.isNaN('1.2.3'); // false
Number.isNaN(Number('1.2.3')); // true

仅供参考,这不适用于 IE。 检查 here 浏览器兼容性。

在我的例子中,我想将 5(整数)、5.4(小数)、'5'、'5.4' 视为数字,但除此之外别无其他。

如果您有类似的需求,下面的可能会更好:

const isNum = num => /^\d+$/.test(num) || /^\d+\.\d+$/.test(num);

//Check your variable if it is a number.
let myNum = 5;
console.log(isNum(myNum))

要包括负数:

const isNum = num => /^-?\d+$/.test(num) || /^-?\d+\.\d+$/.test(num);

这也将消除全局使用 isNaN 的问题。 如果将 isNum 函数转换为普通的 ES5 函数,它也可以在 IE 浏览器上运行。

@Andy Gaskell isNumber('1.2.3') return true,您可能想要编辑您的答案并使用 Number() 代替 parseFloat()

    const isEmpty = value => typeof value === 'undefined' || value === null || value === false;
    const isNumeric = value => !isEmpty(value) && !Number.isNaN(Number(value));
  console.log(isNumeric('5')); // true
  console.log(isNumeric('-5')); // true
  console.log(isNumeric('5.5')); // true
  console.log(isNumeric('5.5.5')); // false
  console.log(isNumeric(null)); // false
  console.log(isNumeric(undefined)); // false

对我来说这很好用,ESlint 没有任何问题

window.isNaN()