1. 程式人生 > >js的顯性型別轉換Number(num)

js的顯性型別轉換Number(num)


js的顯式轉換Number(num)

var a = 1 + 1;
typeof( a );
//打印出number,a = 2 ,a為number型別
var a = 1 + "1";
typeof( a );//打印出string,a = "11",a為string型別,數字與字串相加,數字將顯性轉化為字串
var a = "123";
var b =  Number(a);
typeof( b );
//打印出Number,b = 123,b為number型別
var a = "-12";
var b = Number(a);
typeof( b );
//列印number,b = -12,b為number型別 
var a = true;
var b = Number(a);
typeof(b);
//列印為number,b = 1; 
var a = false;
var b = Number(a);
typeof(b);
console.log(b);
//列印number型別,b = 0
var a = null;
var b = Number( a );
 typeof( b );
console.log( b );
//列印number型別, b = 0; 
var a = undefined;
var b = Number( a );
 typeof( b );
console.log( b );
//列印為number型別, b = NaN
var a = -Infinity;
var b = Number( a );
 typeof( b );
console.log( b );
//列印number型別, b = -Infinity

var a = window;
var b = Number( a );
 typeof( b );
console.log( b );
//列印number型別, b = NaN
var a = [12,243,154];
var b = Number( a );
 typeof( b );
console.log( b );
//列印number型別, b = NaN
var a = 1 -"1" ;
var b = Number( a );
 typeof( b );
console.log( b );
//列印number型別, b = 0
var a = 4 + "2af" ;
var b = Number( a );
 typeof( b );
console.log( b );
//列印Number型別, b = NaN
Number( num )會將裡面的num值轉化為number型別,如果無法轉化為數字,就會成NaN.不管怎樣型別一直是Number型別