JavaScript/显式类型转换
外观
typeof
[编辑]运算符typeof提供表达式的数据类型信息:
console.log(typeof("123"));
console.log(typeof("Hello"));
console.log(typeof("false"));
//均为string
console.log(typeof(10));
console.log(typeof(10.24));
console.log(typeof(NaN));
console.log(typeof(Infinity));
//均为number
console.log(typeof(true));
console.log(typeof(false));
//均为boolean
console.log(typeof( [] ));
console.log(typeof( {} ));
console.log(typeof( null ));
//均为object
console.log(typeof( function(){} ));
//为function
console.log(typeof( ID ));
var a;
console.log(typeof( a ));
//均为undefined
六种显式类型转换
[编辑]- Number(mix)
- parseInt(string,radix)
- parseFloat(string)
- toString(radix)
- String(mix)
- Boolean()
Number
[编辑]如果不能转化为number,则结果为NaN
var a = Number("123");
console.log(typeof(a) + " : " + a);
var b = Number(true);
console.log(typeof(b) + " : " + b);
var c = Number(false);
console.log(typeof(c) + " : " + c);
var d = Number(null);
console.log(typeof(d) + " : " + d);
var e = Number(undefined);
console.log(typeof(e) + " : " + e);
var f = Number("abc");
console.log(typeof(f) + " : " + f);
var g = Number("123abc");
console.log(typeof(g) + " : " + g);
parseInt
[编辑]parseInt(string,radix)解析字符串从左开始的整数部分,至不可解析为止。如果没有整数部分,则返回NaN
console.log(parseInt(123));
console.log(parseInt(123.9));
console.log(parseInt("123"));
console.log(parseInt("123.5"));
console.log(parseInt("123.5.9"));
console.log(parseInt("abc"));
console.log(parseInt("123.8abc"));
console.log(parseInt(true));
console.log(parseInt(false));
console.log(parseInt(undefined));
parseFloat
[编辑]parseFloat(string)
String
[编辑]console.log(String(16) + " : " + typeof(String(16)));
console.log(String(true) + " : " + typeof(String(true)));
console.log(String(undefined) + " : " + typeof(String(undefined)));
console.log(String(null) + " : " + typeof(String(null)));
Boolean
[编辑]只有下述7种情形结果为false。
console.log(Boolean(""));
console.log(Boolean(null));
console.log(Boolean(undefined));
console.log(Boolean(0));
console.log(Boolean(-0));
console.log(Boolean(false));
console.log(Boolean(NaN));
toString
[编辑]作为String的方法,toString可以指明基底。
var demo1 = 16;
var a = demo1.toString(2);
console.log(a + " : " + typeof(a));
//将16 转化成二进制数
var demo3 = 15;
var c = demo3.toString(16);
console.log(c + " : " + typeof(c));
//15转化成16进制数