JavaScript數(shù)據(jù)類型轉換

來源 |?http://www.fly63.com/article/detial/10115
前言
一、強制轉換
1、其他的數(shù)據(jù)類型轉換為String
方式一:toString()方法
var a = 123a.toString()//"123"var b = null;b.toString()//"報錯"var c = undefinedc.toString()//"報錯"
var iNum = 10;alert(iNum.toString(2)); //輸出 "1010"alert(iNum.toString(8)); //輸出 "12"alert(iNum.toString(16)); //輸出 "A"
方式二:String()函數(shù)
但是對于null和undefined,就不會調(diào)用toString()方法,它會將null直接轉換為"null",將undefined 直接轉換為"undefined"。
var a = nullString(a)//"null"var b = undefinedString(b)//"undefined"
String({a: 1}) // "[object Object]"String([1, 2, 3]) // "1,2,3"
2、其他的數(shù)據(jù)類型轉換為Number
方式一:使用Number()函數(shù)
Number('324') // 324Number('324abc') // NaNNumber('') // 0
Number(true) // 1Number(false) // 0
Number(undefined) // NaN
Number(null) // 0
Number(3.15); //3.15Number(023); //19Number(0x12); //18Number(-0x12); //-18
Number({a: 1}) // NaNNumber([1, 2, 3]) // NaNNumber([5]) // 5
方式二:parseInt() & parseFloat()
console.log(parseInt('.21')); //NaNconsole.log(parseInt("10.3")); //10console.log(parseFloat('.21')); //0.21console.log(parseFloat('.d1')); //NaNconsole.log(parseFloat("10.11.33")); //10.11console.log(parseFloat("4.3years")); //4.3console.log(parseFloat("He40.3")); //NaN
console.log(parseInt("13")); //13console.log(parseInt("11",2)); //3console.log(parseInt("17",8)); //15console.log(parseInt("1f",16)); //31
parseInt('42 cats') // 42Number('42 cats') // NaN
另外,對空字符串的處理也不一樣。
Number(" "); //0parseInt(" "); //NaN
3、其他的數(shù)據(jù)類型轉換為Boolean
Boolean(undefined) // falseBoolean(null) // falseBoolean(0) // falseBoolean(NaN) // falseBoolean('') // false
Boolean({}) // trueBoolean([]) // trueBoolean(new Boolean(false)) // true
二、自動轉換
1、自動轉換為布爾值
if ('abc') {console.log('hello')} // "hello"
2、自動轉換為數(shù)值
true + 1 // 22 + null // 2undefined + 1 // NaN2 + NaN // NaN 任何值和NaN做運算都得NaN'5' - '2' // 3'5' * '2' // 10true - 1 // 0'1' - 1 // 0'5' * [] // 0false / '5' // 0'abc' - 1 // NaN
+'abc' // NaN-'abc' // NaN+true // 1-false // 0
3、自動轉換為字符串
'5' + 1 // '51''5' + true // "5true"'5' + false // "5false"'5' + {} // "5[object Object]"'5' + [] // "5"'5' + function (){} // "5function (){}"'5' + undefined // "5undefined"'5' + null // "5null"
三、總結
1、強制轉換的各種情況

2. 自動轉換的的各種情況

評論
圖片
表情
