JavaScript数据类型转换

来源 | http://www.fly63.com/article/detial/10115
前言
一、强制转换
1、其他的数据类型转换为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()函数
但是对于null和undefined,就不会调用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、其他的数据类型转换为Number
方式一:使用Number()函数
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、其他的数据类型转换为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、自动转换为数值
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. 自动转换的的各种情况

评论
