Number 和 parseInt 区别

把字符串 转换成 数字的时候, Number 有点不靠谱, 因为会对 '' 和 null 转换成0, parseInt 相对靠谱些;

判断是否是数值时, isNaN 对于字符串'2'的判断是数字, 对 null 和 '' 也是数字, 所以也是不靠谱;

另外注意 typeof NaN 为 'number', 说明 typeof 判断数字也是不靠谱。

Number(''); // 0

Number(null); // 0

Number(undefined); //NaN

parseInt(''); // NaN

parseInt(null); // NaN

parseInt(undefined); // NaN

isNaN(2); // false

isNaN('2'); // false

isNaN(null); // false, 由于 Number(null) -> 0

isNaN(''); // false, 由于 Number('') -> 0

isNaN(undefined); // true

isNaN(NaN); // true

typeof NaN; // 'number'

原文地址:https://www.cnblogs.com/zhengming2016/p/6992109.html