js中如何判断数据类型

第一种:typeof

typeof(function(){})  //"function"
typeof({}) //"object"
typeof(new Date()) //"object"
typeof(Date()) //"string"
typeof(RegExp('123')) //"object"
typeof([]) //"object"
typeof("123") //"string"
typeof(123)  //"number"
typeof(null) //"object"
typeof(undefined) // "undefined"
typeof(true) //"boolean"
typeof(Symbol) //"function"

可以看到引用类型的数据([]和{})均返回object。同时,typeof也无法辨别像Date,RegExp等特殊的数据类型。Symbol类型和函数均返回function,然后看一看第二种方案:toString.call()

toString.call(Symbol) //"[object Function]"
toString.call(function(){}) //"[object Function]"
toString.call(true) //"[object Boolean]"
toString.call(new Date()) //"[object Date]"
toString.call(Date()) //"[object String]"
toString.call(RegExp('123')) //"[object RegExp]"
toString.call(null) //"[object Null]"
toString.call(undefined) //"[object Undefined]"
toString.call("123") //"[object String]"
toString.call(123) //"[object Number]"
toString.call([]) //"[object Array]"
toString.call({}) //"[object Object]"

[]和{}使用toString.call()得到了区分,但是Symbol类型和函数的返回仍然一致。最后看一下第三种方案:constructor

var fun = function(){}; fun.constructor === Function //true
var sym = Symbol(); sym.constructor  === Symbol //true

值得注意的是,Date数据类型只有在new的时候才会是Date数据类型,否则是字符串类型

var date = new Date(); date.constructor  === Date //true
var date = Date();  date.constructor   === String //true
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值