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]

第三种方法,最为齐全。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值