number數字類型
包含:常規數字,NaN
NaN
not a number:不是一個數,但是他率屬於數字類型
<script src = "test.js"></script>
//test.js
//console.log([val]):
//console.log("hello word!");
// ==:進行比較的
console.log('AA' == NaN);//false
console.log(10 == NaN);//false
console.log(NaN == NaN);//false
NaN和任何值(包括自己)都不相等:NaN!=NaN,所以我們不能用相等的方式判斷是否為有效數字
isNaN
檢測一個值是否為非有效數字,如果不是有效數字返回ture,反之是有效數字返回false
//isNaN([val])
console.log(isNaN[10]);//=>false
console.log(isNaN['AA']);//=>ture
//Number('AA') => NaN
//isNaN(NaN) => true
console.log(isNaN['10']);//=>false
//Number('10') => 10
//isNaN(10) => false
如果在使用isNaN進行有效數字檢測的時候,首先會驗證檢測的值是否為數字類型,如果不是先基於Number()這個方法,把值轉換為數字類型,然后再檢測
把其它類型值轉換為數字類型
把字符串轉換為數字,只要字符串中包含任意一個非有效數字字符(第一個點除外)結果都是NaN,空字符串會變為數字零
- Number([val])
- parseInt/parseFloat([val],[進制]):也是轉換為數字的方法,對於字符串來說,它是從左到右依次查找有效數字字符,直到遇到非有效數字字符,停止查找(不管后面是否還是數字,都不在找了),把找到的當作數字返回
console.log(Number('12.5'));//=>12.5
console.log(Number('12.5px'));//=>NaN
console.log(Number(1.5.5));//=>NaN
console.log(Number(''));//空=>0
//布爾轉換數字
console.log(Number(true));//=>1
console.log(Number(false));//=>0
console.log(isNaN(false));//=>false
//null->0 undefined->NaN
console.log(Number(null));//=>0
console.log(Number(undefined));//=>NaN
//把引用數據類型轉換為數字,是先把他基於toString方法
console.log(Number({name:'10'}));//引用數據類型=>NaN
console.log(Number({}));//=>NaN
//{XX}.toString()=>"[object Object]"=>NaN
cosole.log(Number([]));=>0
//([]).toString() -> ''
console.log(Number([12]))//=>12
//[12].toString(); -> '12'
console.log(Number([12,23]));//=>NaN
//[12,23].toString() -> '12,23'
let str = '12.5px';
console.log(Number(str));//=>NaN
console.log(parseInt(str));//=>12
console.log(pareInt(str));//=>12.5
console.log(pareFloat('width:12.5px'));//=>NaN