js判斷數據類型的3種方法

js判斷數據類型的3種方法

var a = {}			//對象
var b = []			//數組
var c = 1			//數字
var d = 'foo'		//字符串
var e = true		//布爾值
var f = function(){}	//函數
var g = null		//null
var h = undefined	//未定義類型

// 1. typeof
typeof(a)  // object
typeof(b)  // object
typeof(c)  // number
typeof(d)  // string
typeof(e)  // boolean
typeof(f)  // function
typeof(g)  // object
typeof(h)  // undefined
 
 	//這種方法數組和null都會被判斷爲對象

//2. instanceof 用來判斷已知類型
a instanceof  Object  	 //true
f instanceof  Function   //true

//3. Object.prototype.toString.call()
Object.prototype.toString.call(a)  //[object Object]
Object.prototype.toString.call(b)  //[object Array]
Object.prototype.toString.call(c)  //[object Number]
Object.prototype.toString.call(d)  //[object String]
Object.prototype.toString.call(e)  //[object Boolean]
Object.prototype.toString.call(f)  //[object Function]
Object.prototype.toString.call(g)  //[object Null]
Object.prototype.toString.call(h)  //[object Undefined]

第三種方法,最爲齊全。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章