

NaN
“执行数学运算没有成功,这是失败后返回的结果”
NaN==NaN`` // falseNaN!=NaN `` // truetypeof NaN; `` // "number"0`` / 0`` // NaN3 / 0`` // Infinity'aaa' / 0 `` // NaN
isNaN()
接收参数后,会尝试将这个参数转换为数值,任何不能被转换为数值的的值都会返回 tru**e**,因此非数字值传入也会返回 true ,会影响 NaN 的判断。
Number.isNaN()
如果参数类型不是NaN,Number.isNaN一律返回false
isNaN('NaN'); // trueisNaN(undefined); // trueisNaN({}); // trueNumber.isNaN("NaN"); // false,字符串 "NaN" 不会被隐式转换成数字 NaN。Number.isNaN(undefined); // falseNumber.isNaN({}); // false
对比isNaN(undefined) : // true ,隐式转换:undefined无法转成数字isNaN(null) : // false ,隐式转换:null可以转成数字0
Number.parseInt()
参数:(string [,radix])
string:要被解析的值。如果参数不是一个字符串,则将其转换为字符串 ,radix:2~36,表示字符串的基数。如: 16 表示被解析值是十六进制数。- 请注意:10不是默认值!
- ES5中
0默认使用10进制
parseInt遇到的字符不是指定radix参数中的数字,它将忽略该字符以及所有后续字符,并返回到该点为止已解析的整数值。- 当非常大或非常小的数字使用
e表示时,使用parseInt截断数字将产生意外结果。parseInt不应替代Math.floor()。
- 如果第一个字符不能转换为数字,
parseInt会返回NaNparseInt(10,8) // 8parseInt(6.022e23) // 6 :不要对太大数使用parseIntparseInt(12,2) // 1 : "2"超过基数,舍弃parseInt(12512,4) // 6 : "5"超过基数,此数及后续舍弃 -> 12(4进制) -> 6parseInt('1314ba') // 1314 : "ba"舍弃
面试题:
```javascript // arr输出? let arr = [1,2,3,4] arr = arr.map(parseInt)
/分析/ map(fun(item,index){}); // 注:fun没有调用哦
// 故依次传参为: parseInt(1,0) : 1 parseInt(2,1) :NaN parseInt(3,2) :NaN parseInt(4,3) :NaN
故最终输出 [1,NaN,NaN,NaN]
<a name="QfO2G"></a>### `Number.parseFloat(string)````javascriptparseFloat(3.14);parseFloat('3.14');parseFloat('3.14some non-digit characters');
其他值到数字值的转换规则?
Undefined类型的值转换为NaN。Null类型的值转换为0。Boolean类型的值,true转换为1,false转换为0。String类型的值转换如同使用 Number() 函数进行转换,如果包含非数字值则转换为 NaN,空字符串为 0。Symbol类型的值不能转换为数字,会报错。对象(包括数组)会遵循ToPrimitive操作, 会先后valueOf()方法和toString()方法,看是否能返回基本类型值- 若能返回基本类型值,来按照前5条进行强制类型转换。
- 均不返回基本类型值,会产生 TypeError 错误。
console.log(Number({})) // NaNconsole.log(Number({a : 1})) // NaNconsole.log(Number([])) // 0 : [] -> "" -> 0console.log(Number([0])) // 0 : [0] -> "0" -> 0console.log(Number([1, 2, 3])) // NaN : [1, 2, 3] -> "1,2,3" -> NaNconsole.log(Number(function(){var a = 1;})) // NaNconsole.log(Number(/\d+/g)) // NaNconsole.log(Number(new Date(2010, 0, 1))) // 1262275200000console.log(Number(new Error('a'))) // NaN

