js判斷數據類型的三種方法(文章最後有快捷方法哦!)

js判斷數據類型的方法有很多種,本文只選擇三種使用頻率較高的方法來說明,這裏比較推崇使用第三種方法,閒話少說下面開始介紹:

1、typeof

typeof new String( 'bart' ); // object
typeof 'bart'; // string
typeof 10; // number
typeof true; // boolean
typeof null; // object  ->  這是bug,但永遠不會修復,所以我們注意就行了!
typeof undefined; // undefined

大家可能注意到了前兩行都是字符串,但是爲什麼返回的一個是 string 一個是 object 呢?這是因爲雖然都是字符串,但是創建方式和存儲方式不一樣,一個是堆內存,一個是棧內存,所以導致了這種特殊性,這裏不做過多介紹,只是說明使用 typeof 進行數據類型判斷需要注意的情況( 你不這樣寫,不代表你的團隊好基友不會這樣寫? ),有興趣可以自行查閱堆內存和棧內存的區別。

2、instanceof

判斷對象A是否爲對象B的實例
// 這裏小小封裝一下,小小的解釋一下:
// isInstanceof 封裝了一下 instanceof 方法,調用時傳入兩個參數
如果第一個參數的原型是第二個參數,那麼返回 true,否則返回 false

let isInstance = function( A, B ) {
	return A instanceof B
}isInstance( new Number( 10 ), Number ); // true
isInstance( new String( 'bart' ), String ); // true
isInstance( new Boolean( false ), Boolean ); // true
isInstance( {}, Object ); // true

3、toString

Object.prototype.toString.call( 'bart' ); // [object String] 對比
Object.prototype.toString.call( new String( 'bart' ) ); // [object String] 對比
Object.prototype.toString.call( 10 ); // [object Number]
Object.prototype.toString.call( function(){} ); // [object Function]
Object.prototype.toString.call( { name: 'bart' } ); // [object Object]
Object.prototype.toString.call( Symbol() ); // [object Symbol]
Object.prototype.toString.call( new Date() ); // [object Date]
Object.prototype.toString.call( [ 1, 2, 3 ] ); // [object Array]

大家發現我標記的前兩行,兩種創建字符串的方式都可以精確地判斷出來爲 [object String] ,但是這樣使用起來代碼很多,而且可讀性很差,所以這裏借鑑 《JavaScript設計模式與開發實踐》 的部分代碼並小小改動提供兩種封裝使用 toString 的模式

① 把借用 Object.prototype.toString 的過程封裝起來

let isType = function( type ) {
	return function( obj ) {
		return Object.prototype.toString.call( obj ) === `[object ${type}]`
	}
};

let isString = isType( 'String' );
isString( 'bart' ); // true
isString( new String( 'bart' ) ); // true

② 使用循環註冊要使用的方法

let Type = {};
let registerType = [ 'String', 'Number', 'Array' ]; // 註冊使用哪種類型直接寫到這個數組裏就可以了

for ( let i = 0, type; type = registerType[i++]; ) {
	(function( type ){
		Type[ `is${type}` ] = function( obj ) {
			return Object.prototype.toString.call( obj ) === `[object ${type}]`;
		}
	})( type );
};

Type.isString( 'bart' ); // true
Type.isString( new String( 'bart' ) ); // true
發佈了28 篇原創文章 · 獲贊 6 · 訪問量 2025
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章