意外使用 isNaN

我试图在 Node.js 模块的一个 Arrow 函数中使用 isNaN全局函数,但是我得到了这个错误:

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

这是我的暗号:

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


module.exports = {
isNumber,
};

知道我哪里做错了吗?

附注: 我使用的是 AirBnB 风格指南。

73519 次浏览

作为 文件显示,使用 Number.isNaN

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

引用 Airbnb 的文档:

< p > 为什么? global isNaN 将非数字强制转换为数字,返回 true 任何强迫 NaN 的行为。如果需要这种行为,请 非常明确
// 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 不起作用。 在浏览器兼容性检查 给你

在我的例子中,我希望将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')返回 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

对我来说,这个工作很好,没有任何问题与埃斯林特

window.isNaN()