方法一、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
推薦教程:js入門教程
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com