1. 程式人生 > >JS函式之判斷資料型別程式碼

JS函式之判斷資料型別程式碼

//定義變數 var a=1, b, c=null, d=[], e={}; //宣告getType函式 function getType(x){ //利用typeof判斷資料型別,得到number型別、undefinded型別、object型別 if(typeof x == 'object'){ // //使用instanceof判斷某變數是否屬於某物件 if(x instanceof Array){ //返回結果
return 'array'; }else if(x instanceof Object){ return 'object'; }else{ return 'null'; } }else{ //返回資料型別 return typeof x; } } // 呼叫函式並輸出
console.log(getType(e));