農林漁牧網

您現在的位置是:首頁 > 農業

一行程式碼實現資料型別判斷

2023-01-09由 文江部落格 發表于 農業

如何確定資料型別

一行程式碼實現資料型別判斷

JS 判斷資料型別,方法有很多,如 typeof、constructor、toString 等等,甚至可以使用 jQuery 內部的 $。type 都可以判斷。其中 typeof 等的判斷侷限性都比較大,如 typeof 只能判斷資料儲存型別,constructor 只能判斷資料的原型,toString 相對比較完整一點,但顯示不夠友好,在 jQuery 中對其做了一些修飾,正是

Object。prototype。toString

的功勞。

Object。prototype。toString。call(1)// “[object Number]”Object。prototype。toString。call(‘1’)// “[object String]”Object。prototype。toString。call({})// “[object Object]”Object。prototype。toString。call([])// “[object Array]”Object。prototype。toString。call(window)// “[object global]”

注意到了嗎?每個資料型別的返回值都有一個相同點,那就是

[object]

,透過取值後面的文字可以獲取到該物件的資料型別。即:

Object。prototype。toString。call(object)。slice(8, -1)。toLowerCase();Object。prototype。toString。call(1)。slice(8, -1)。toLowerCase();// “number”Object。prototype。toString。call(‘1’)。slice(8, -1)。toLowerCase();// “string”Object。prototype。toString。call({})。slice(8, -1)。toLowerCase();// “object”Object。prototype。toString。call([])。slice(8, -1)。toLowerCase();// “array”Object。prototype。toString。call(window)。slice(8, -1)。toLowerCase();// “global”

初始的

typeis

就是這樣的:

/** * 判斷資料型別 * @param obj {*} 任何資料 * @returns {string} */var typeis = function (obj) { return Object。prototype。toString。call(obj)。slice(8, -1)。toLowerCase();};

透過測試可知:

typeis(NaN);// “number”

不太符合預期,需要額外判斷一次

/** * 判斷資料型別 * @param obj {*} 任何資料 * @returns {string} */var typeis = function (obj) { var ret = Object。prototype。toString。call(obj)。slice(8, -1)。toLowerCase(); if(isNaN(obj) && ret === ‘number’){ return ‘nan’; } return ret;};

判斷 element 元素的時候:

typeis(document。body)// “htmlbodyelement”typeis(document。head)// “htmlheadelement”

不符合預期,再修改:

/** * 判斷資料型別 * @param obj {*} 任何資料 * @returns {string} */var typeis = function (obj) { var ret = Object。prototype。toString。call(obj)。slice(8, -1)。toLowerCase(); if (isNaN(obj) && ret === ‘number’) { return ‘nan’; } else if (/element/。test(ret)) { return ‘element’; } return ret;};

最後再對一些全域性物件,做些處理:

/** * 判斷資料型別 * @param obj {*} 任何資料 * @returns {string} */var typeis = function (obj) { var udf = ‘undefined’; if (typeof obj === udf) { return udf; } else if (typeof window !== udf && obj === window) { return ‘window’; } else if (typeof global !== udf && obj === global) { return ‘global’; } else if (typeof document !== udf && obj === document) { return ‘document’; } else if (obj === null) { return ‘null’; } var ret = Object。prototype。toString。call(obj)。slice(8, -1)。toLowerCase(); if (isNaN(obj) && ret === ‘number’) { return ‘nan’; } else if (/element/。test(ret)) { return ‘element’; } return ret;};

一個比較完善、完整的 typeis 就出來了。