js 判断数字

原文链接
有空翻译一下

The purpose of isNaN is not to check if a value is nummeric or not. It actual purpose is to check if a floating point number has the special value of NaN. The special NaN value is assigned to the results of mathematically impossible operations, like dividing 0/0 or converting an alphabetic string to a number.

However, when you try to use isNaN on a value which is not a floating-point number, Javascript first tries to convert it to a number and then checks if that number has the special NaN value. To make matters more confusing, undefined is also treated as NaN by Javascript, so when the value can not be converted to a number, it is considered NaN.

To protect yourself from headache, only use isNaN when you are really looking for the floating point NaN value.

When you want to know if a variable is a number, use typeof variable == 'number' (the value of NaN is also of type number, by the way). When you want to know if a string can be converted to a number, use isNaN(Number(variable)).

你可能感兴趣的:(js 判断数字)