1. 程式人生 > >JS判斷變量類型

JS判斷變量類型

split fin date 檢測 class define lean raw 無法

目前接觸到的共有四種方法:

1、typeof,

typeof對大多數的類型判斷都是正確的,但是無法區分數組,null,和真正的Object,它的判斷都是Object。

2、Object.prototype.toString.call(),

Object.prototype.toString.call()的方法,各種類型都合適,判斷準確,也是我準備長期使用的一種方法,返回的結果如[Object Array],據我所知,jQuery的內部工具、vue的內部工具,mock的內部工具,都是采用的這種方法。

jQuery實現方法,采用對象方式存儲,

初始化變量class2type={},

// Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); 然後類型判斷方法: type: function( obj ) { if ( obj == null ) { return String( obj ); } return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : // 返回對象中有的結果 typeof obj; // 返回typeof本身可以判斷的。 } Vue內部判斷方法,簡單粗暴:
var _toString = Object.prototype.toString; function toRawType (value) { return _toString.call(value).slice(8, -1) // 直接從第八位返回到倒數第二位 } Mock的內部工具方法,使用正則: Util.type = function type(obj) { return (obj === null || obj === undefined) ? String(obj) : Object.prototype.toString.call(obj).match(/\[object (\w+)\]/)[1].toLowerCase() }

3、instanceof

MDN給出的解釋是:instanceof 運算符用來檢測 constructor.prototype 是否存在於參數 object 的原型鏈上。

instanceof右側要求是對象,而不能是null或者undefined,否則會拋出異常。

測試了以下場景:

字符串:

var a = ‘‘; a instanceof String // false

var a = new String(‘‘); a instanceof String //true,

數字:

var a = 3; a instanceof Number // false

var a = new Number(3); a instanceof Number //true,

數組:

var a= [1,2,3]; a instanceof Array //true

var a = new Array(1,2,3); a instanceof Array //true

函數:

var a = function(){} a instanceof Fuction // true

var a = new Function(); a instanceof Function //true

// 對象

var a= {};a instanceof Object //true

// 正則

var a= /ppp/; a instanceof RegExp // true

// undefined,null的沒法說了

總結:凡是簡單字面量的像number,string的必須用new才識別,而復雜點的像數組,對象,函數,正則都可以直接用。但是原型鏈上的返回都是true,比如

var a = new String(‘‘); a instanceof String // true, a instanceof Object肯定也是true.

4、constructor.name

該方式大部分情況下都可以,弊端是undefined,或者null沒有constructor。好像跟3有點像,3是表示constructor.prototype,首先得有constructor才能有constructor.prototype。

用法例:

var a = ‘‘

a.constructor.name // 返回String

很是推薦第二種,最全。

JS判斷變量類型