首頁  >  文章  >  web前端  >  js中如何判斷資料型別

js中如何判斷資料型別

王林
王林轉載
2020-05-13 09:18:403884瀏覽

js中如何判斷資料型別

方法一、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入門教學

以上是js中如何判斷資料型別的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:cnblogs.com。如有侵權,請聯絡admin@php.cn刪除