检查字符串是否为数字的最可靠方法是什么?
var checkForNumber = (arg) => {
if (typeof arg === 'number') {
return arg + ' is a number'
} else if (Number(arg)) {
return arg + ' is a number'
}
return 'Not a number';
};
checkForNumber('a')
我考虑检查数字的最好方法是函数isNaN((,"不是数字"与"是数字"相反
>isNaN(1)
false
>isNaN('1')
false
>isNaN('1e')
true
>isNaN('1.1')
false
>isNaN('1,1')
true
>isNaN('0000001')
false
>isNaN('f12f')
true
你应该把这个函数用为否定的:!isNaN((
鉴于Number()
的构造函数如果无效将返回NaN
,我认为这可能是获取有关数字是否有效的布尔值的好方法:
function isNum(num) {
return (
!isNaN(num) &&
(parseInt(num) == num || parseFloat(num) == num)
);
}
console.log('"1"', isNum('1'));
console.log('1', isNum(1));
console.log('"a"', isNum('a'));
console.log('empty string', isNum(''));
console.log('object', isNum({}));
console.log('undefined', isNum(undefined));
console.log('false', isNum(false));
console.log('true', isNum(true));
console.log('[]', isNum([]));
console.log('PI short string', isNum('3.14'));
console.log('PI short float', isNum(3.14));
console.log('PI long', isNum(3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679));
您还必须检查布尔值还是数组,因为它们将作为数字返回。我是通过比较parseInt的输出来做到这一点的。