跳至內容

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进制数