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]

第三种方法,最为齐全。

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