[英]ESLint Unexpected use of isNaN
I'm trying to use the isNaN
global function inside an arrow function in a Node.js module but I'm getting this error:我正在尝试在 Node.js 模块中的箭头函数内使用
isNaN
全局函数,但出现此错误:
[eslint] Unexpected use of 'isNaN'. (no-restricted-globals)
This is my code:这是我的代码:
const isNumber = value => !isNaN(parseFloat(value));
module.exports = {
isNumber,
};
Any idea on what am I doing wrong?知道我做错了什么吗?
PS: I'm using the AirBnB style guide. PS:我使用的是 AirBnB 风格指南。
As the documentation suggests , use Number.isNaN
.正如文档所建议的,使用
Number.isNaN
。
const isNumber = value => !Number.isNaN(Number(value));
Quoting Airbnb's documentation:引用Airbnb的文档:
Why?
为什么? The global isNaN coerces non-numbers to numbers, returning true for anything that coerces to NaN.
全局 isNaN 将非数字强制转换为数字,对于任何强制转换为 NaN 的内容返回 true。 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
@Andy Gaskell isNumber('1.2.3')
return true
, you might want to edit your answer and use Number()
in place of parseFloat()
@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
In my case, I wanted to treat 5 (integer), 5.4(decimal), '5', '5.4' as numbers but nothing else for example.就我而言,我想将 5(整数)、5.4(十进制)、'5'、'5.4' 视为数字,但仅此而已。
If you have the similar requirements, below may work better:如果您有类似的要求,以下可能会更好:
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))
To include negative numbers:要包含负数:
const isNum = num => /^-?\d+$/.test(num) || /^-?\d+\.\d+$/.test(num);
This will remove your issue of global use of isNaN as well.这也将消除您在全局使用 isNaN 的问题。 If you convert the isNum function to a normal ES5 function, it will work on IE browser as well.
如果将 isNum 函数转换为普通的 ES5 函数,它也可以在 IE 浏览器上运行。
对我来说,这很好用,ESlint 没有任何问题
window.isNaN()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.