What causes isNaN to malfunction?
本问题已经有最佳答案,请猛点这里访问。
我只是想评估一个输入是否是一个数字,计算出
| 1 2 3 4 | function isNumerical(value) { var isNum = !isNaN(value); return isNum ?"<mark>numerical</mark>" :"not numerical"; } | 
关于这些值:
| 1 2 3 4 5 6 | isNumerical(123));     // => numerical isNumerical("123")); // => numerical isNumerical(null)); // => numerical isNumerical(false)); // => numerical isNumerical(true)); // => numerical isNumerical()); // => not numerical | 
号
如图所示:http://jsfiddle.net/4nm7r/1
为什么
如果传递的值不是数字(NaN)(或不能转换为数字,那么,
很容易理解脚本的行为。
您不能将任何值与
无论如何,您可以通过执行以下操作来修复代码:
| 1 2 3 4 | function isNumerical(value) { var isNum = !isNaN(value / 1); //this will force the conversion to NaN or a number return isNum ?"<mark>numerical</mark>" :"not numerical"; } | 
我建议您使用其他支票:
| 1 2 3 4 | function isNumerical(value) { var isNum = !isNaN(value) && value !== null && value !== undefined; return isNum ?"<mark>numerical</mark>" :"not numerical"; } | 
。
如果您希望将像
| 1 | var isNum = !isNaN(value) && value !== null && value !== undefined && (typeof value === 'number'); | 
。
既然你已经修正了其他答案所指出的逆向逻辑,那么就用
| 1 | var isNum = !isNaN(parseFloat(value)); | 
。
请记住,
| 1 2 3 4 | parseFloat("200$"); // 200 parseFloat("200,100"); // 200 parseFloat("200 foo"); // 200 parseFloat("$200"); // NaN | 
(即,如果字符串以数字开头,ParseFloat将提取它能找到的第一个数字部分)
你的三元语句是向后的,如果
| 1 | return isNum ?"not numerical" :"<mark>numerical</mark>"; | 
号
应该是:
| 1 | return isNum ?"<mark>numerical</mark>" :"not numerical"; | 
参见更新的小提琴:
http://jsfiddle.net/4nm7r/1/