javascript判斷數據類型有哪些方法?這篇文章運用了實例代碼展示,代碼非常詳細,可供感興趣的小伙伴們參考借鑒,希望對大家有所幫助。
方法一、js內置方法typeof
檢測基本數據類型的最佳選擇是使用typeof
typeof 來判斷數據類型,只能區分基本類型,即 “number”,”string”,”undefined”,”boolean”,”object”,“function”,“symbol” (ES6新增)七種。
對于數組、null、對象來說,其關系錯綜復雜,使用 typeof 都會統一返回 “object” 字符串。
示例:
var bool = true
var num = 1
var str = 'abc'
var und = undefined
var nul = null
var arr = [1,2,3]
var obj = {}
var fun = function(){}
var reg = new RegExp()
console.log(typeof bool); //boolean
console.log(typeof num); //number
console.log(typeof str); //string
console.log(typeof und); //undefined
console.log(typeof nul); //object
console.log(typeof arr); //object
console.log(typeof obj); //object
console.log(typeof reg); //object
console.log(typeof fun); //function由結果可知,除了在檢測null時返回 object 和檢測function時放回function。對于引用類型返回均為object。
方法二、Object.prototype.toString()
Object.prototype.toString方法返回對象的類型字符串,因此可以用來判斷一個值的類型。
var obj = {};
obj.toString() // "[object Object]"上面代碼調用空對象的toString方法,結果返回一個字符串object Object,其中第二個Object表示該值的構造函數。這是一個十分有用的判斷數據類型的方法。Object.prototype.toString.call(value)
上面代碼表示對value這個值調用Object.prototype.toString方法。
不同數據類型的Object.prototype.toString方法返回值如下。
數值:返回[object Number]。 字符串:返回[object String]。 布爾值:返回[object Boolean]。 undefined:返回[object Undefined]。 null:返回[object Null]。 數組:返回[object Array]。 arguments 對象:返回[object Arguments]。 函數:返回[object Function]。 Error 對象:返回[object Error]。 Date 對象:返回[object Date]。 RegExp 對象:返回[object RegExp]。 其他對象:返回[object Object]。
那么利用這個特性,可以寫出一個比typeof運算符更準確的類型判斷函數。
封裝出一個判斷類型的函數如下:
var type = function (o){
var s = Object.prototype.toString.call(o);
return s.match(/\[object (.*?)\]/)[1].toLowerCase();
};
type({}); // "object"
type([]); // "array"
type(5); // "number"
type(null); // "null"
type(); // "undefined"
type(/abcd/); // "regex"
type(new Date()); // "date"另外:還可以加上專門判斷某種類型數據的方法
var type = function (o){
var s = Object.prototype.toString.call(o);
return s.match(/\[object (.*?)\]/)[1].toLowerCase();
};
var arr = ['Null', 'Undefined', 'Object', 'Array', 'String', 'Number',
'Boolean', 'Function', 'RegExp']
arr.forEach(function (t) {
type['is' + t] = function (o) {
return type(o) === t.toLowerCase();
};
});之后我們可以通過封裝出的方法去在不同需求時使用:如下
type.isObject({}) // true
type.isNumber(NaN) // true
type.isRegExp(/abc/) // true關于javascript判斷數據類型的方法就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果喜歡這篇文章,不如把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。