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)).

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。