使用isNaN函数来判断一个变量是不是数字形式,通过下面代码可能会有更明确的认识:
function checkit(x) {
let v = x;
if (isNaN(x)) {
v = 'Not a Number!';
}else{
v = Number(x);
}
console.log(x,'is',v);
}
checkit('123');
checkit('-123');
checkit('3.14');
checkit('0.0314E+2');
checkit(0xF);
checkit('123F');
checkit('abc');
checkit(null);
checkit(false);
checkit(true);
checkit(undefined);
输入结果:
123 is 123
-123 is -123
3.14 is 3.14
0.0314E+2 is 3.14
15 'is' 15
123F is Not a Number!
abc is Not a Number!
null 'is' 0
false 'is' 0
true 'is' 1
undefined 'is' 'Not a Number!'
需要注意的是:
123F is Not a Number!
null 'is' 0
false 'is' 0
true 'is' 1