1.转换成String
所有基本类型转为String,都是吃什么吐什么。
But!!对于数组和对象类型,如下所示
//Object对象
console.log(String({name:'宠儿',age:16}));
console.log(String({}));//空对象
//都会输出:'[Object Object]'
//Array数组
console.log(String([]));//''
console.log( String( [1,2,3,true,{},] ) );
//输出'1,2,3,true,[object Object]',0
//即把数组里边的每一项都转为字符串,然后用逗号隔开
转换方式:
①调用被转换类型的toString()方法
var a = 123;
a = a.toString();
document.write(typeof a);
注:Null和Undefined没有toString方法
②调用String函数
var a = 123;
a = String(a);
document.write(typeof a);
注:可以用于Null和Undefined
2.转换成Number
①使用Number()函数
字符串—>Number :
- 纯数字–>数字;
- 非数字内容—>NaN
- ”“ 和 ” “---->0
布尔—>Number:
- true—>1
- false—>0
Null—>Number: 0
Undefined —>Number : NaN
对象–>Number:
对象不能直接转换成数字:会先把对象用.toString()转换成字符串,然后再把这个字符串转为数字。(隐式类型转化)
//Obiect
console.log( Number({}) );//NaN
//转换过程:{} --> '[Object Object]' --> NaN
//Array
console.log( Number([]) );//0
console.log( Number([1]) );//1
console.log( Number([1,2]) );//NaN
②专门用来对付字符串
- parseInt()—>获取有效整数
- parseFloat()---->获取有效小数
如果对非String使用parseInt()或parseFloat(),会将其转换成String再操作
其他进制的数字
-
表示十六进制的数字,需要以0x开头;
-
表示八进制的数字,需要以0开头;
-
表示二进制的数字,需要以0b开头
-
此时将会出现一些问题,例如:
var a = "070";
a = parseInt(a);
有些浏览器将a当成八进制解析为56,有些浏览器将a当作十进制解析为70。
解决方案:
var a = "070";
a = parseInt(a,10);
3.转换为Boolean
使用Boolean()函数
-
数字—>布尔 : 除0和NaN,都是true
-
字符串—>布尔: 除了空串,其余都是true
-
Null 和Undefined–>布尔 : false
-
引用类型—>布尔: true
console.log( Boolean(1) );//true
console.log( Boolean(0) );//①false
console.log( Boolean(NaN) );//②false
console.log( Boolean('宠儿') );//true
console.log( Boolean('') );//③false
console.log( Boolean(null) );//④false
console.log( Boolean(undefined) );//⑤false
var obj = { name:'chonger'};
console.log( Boolean(obj) );//true
console.log( Boolean([]) );//true