Javascript ESLint 意外使用 isNaN
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46677774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ESLint Unexpected use of isNaN
提问by Elias Garcia
I'm trying to use the isNaNglobal function inside an arrow function in a Node.js module but I'm getting this error:
我正在尝试isNaN在 Node.js 模块中的箭头函数内使用全局函数,但出现此错误:
[eslint] Unexpected use of 'isNaN'. (no-restricted-globals)
[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 风格指南。
回答by Andy Gaskell
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. If this behavior is desired, make it explicit.
为什么?全局 isNaN 将非数字强制转换为数字,对于任何强制转换为 NaN 的内容返回 true。如果需要这种行为,请使其明确。
// bad
isNaN('1.2'); // false
isNaN('1.2.3'); // true
// good
Number.isNaN('1.2.3'); // false
Number.isNaN(Number('1.2.3')); // true
回答by thyforhtian
回答by Vincent Baronnet
@Andy Gaskell isNumber('1.2.3')return true, you might want to edit your answer and use Number()in place of parseFloat()
@Andy加斯克尔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
回答by Noby Fujioka
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. If you convert the isNum function to a normal ES5 function, it will work on IE browser as well.
这也将消除您在全局使用 isNaN 的问题。如果将 isNum 函数转换为普通的 ES5 函数,它也可以在 IE 浏览器上运行。
回答by Yoannes Geissler
For me this worked fine and didn't have any problem with ESlint
对我来说,这很好用,ESlint 没有任何问题
window.isNaN()
window.isNaN()

