使用js判斷資料型別

2021-08-27 03:45:24 字數 1277 閱讀 6066

出去溜達的時候,也會有人問如何判斷js資料型別,我當時回答是使用

typeof  判斷各種資料型別,有兩種寫法:typeof   ***   ,typeof(***)

console.log(typeof 1 , typeof null, typeof {}, typeof , typeof (function(){}) ,typeof undefined, typeof '222', typeof true)

結果:number object object object function undefined string boolean

緊接著是爛大街的問法是如何區分陣列和物件,我的回答是

使用constructor,來判斷,

console.log(.constructor == array, {}.constructor == object)

結果: true true

剛才突然想到,那如何區分null,undefined ?

可以使用object.prototype.tostring.call,用來更精確的區分資料型別。

var getdatatype=object.prototype.tostring;

console.log(getdatatype.call('字串'), getdatatype.call(1), getdatatype.call(true), getdatatype.call(undefined),getdatatype.call(null), getdatatype.call({}), getdatatype.call(), getdatatype.call(function(){}));

結果:[object string] [object number] [object boolean] [object undefined] [object null] [object object] [object array] [object function]

下面是我封裝的函式,感興趣可以直接使用

const judgetype = ,

isobject (par) ,

isarray (par) ,

isstring (par) ,

isnumber (par) ,

isboolean (par) ,

isundefined (par) ,

isnull (par) ,

isfunction (par)

}

js判斷資料型別

1 typeof 形如 var x xx typeof x string 返回型別有 undefined string number boolean function object 缺點 對於object型別不能細分是什麼型別 優點 對空null的判斷 undefined 的應用 2 instanc...

js判斷資料型別

了解js的都知道,有個typeof 用來判斷各種資料型別,有兩種寫法 typeof typeof 如下例項 typeof 2 輸出 number typeof null 輸出 object typeof 輸出 object typeof 輸出 object typeof function 輸出 fu...

js判斷資料型別

1 判斷是否為陣列型別 2 判斷是否為字串型別 3 判斷是否為數值型別 isnan 變數 如果為true就是數字型別 注意這個函式一般針對數字型別來判斷是否值為nan,若變數為非數字型別,則先轉化為數字型別再做判斷,用此函式時,別忘考慮空串和空格 這倆轉化為數字是0 4 判斷是否為日期型別 5 判斷...