溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Javascript判斷數(shù)據(jù)類型有哪些方法?

發(fā)布時間:2020-05-18 11:36:11 來源:億速云 閱讀:249 作者:Leah 欄目:web開發(fā)

javascript判斷數(shù)據(jù)類型有哪些方法?這篇文章運用了實例代碼展示,代碼非常詳細,可供感興趣的小伙伴們參考借鑒,希望對大家有所幫助。

方法一、js內(nèi)置方法typeof

檢測基本數(shù)據(jù)類型的最佳選擇是使用typeof

typeof 來判斷數(shù)據(jù)類型,只能區(qū)分基本類型,即 “number”,”string”,”undefined”,”boolean”,”object”,“function”,“symbol” (ES6新增)七種。

對于數(shù)組、null、對象來說,其關(guān)系錯綜復(fù)雜,使用 typeof 都會統(tǒng)一返回 “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

由結(jié)果可知,除了在檢測null時返回 object 和檢測function時放回function。對于引用類型返回均為object。

方法二、Object.prototype.toString()

Object.prototype.toString方法返回對象的類型字符串,因此可以用來判斷一個值的類型。

var obj = {};
obj.toString() // "[object Object]"上面代碼調(diào)用空對象的toString方法,結(jié)果返回一個字符串object Object,其中第二個Object表示該值的構(gòu)造函數(shù)。這是一個十分有用的判斷數(shù)據(jù)類型的方法。

Object.prototype.toString.call(value)

上面代碼表示對value這個值調(diào)用Object.prototype.toString方法。

不同數(shù)據(jù)類型的Object.prototype.toString方法返回值如下。

數(shù)值:返回[object Number]。
字符串:返回[object String]。
布爾值:返回[object Boolean]。
undefined:返回[object Undefined]。
null:返回[object Null]。
數(shù)組:返回[object Array]。
arguments 對象:返回[object Arguments]。
函數(shù):返回[object Function]。
Error 對象:返回[object Error]。
Date 對象:返回[object Date]。
RegExp 對象:返回[object RegExp]。
其他對象:返回[object Object]。

那么利用這個特性,可以寫出一個比typeof運算符更準確的類型判斷函數(shù)。

封裝出一個判斷類型的函數(shù)如下:

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"

另外:還可以加上專門判斷某種類型數(shù)據(jù)的方法

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

關(guān)于javascript判斷數(shù)據(jù)類型的方法就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學到更多知識。如果喜歡這篇文章,不如把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI