JavaScript判断数据类型

前一阵写过一个如何判断数据类型的文章,再更新一些。

在 JavaScript 里使用 typeof 来判断数据类型,只能区分基本类型,即 “number”,”string”,”undefined”,”boolean”,”object” 五种。对于数组、函数、对象来说,其关系错综复杂,使用 typeof 都会统一返回 “object” 字符串。

还可以使用instanceof,例如

var arr = [];
if(arr instanceof Array){
    console.log(1);
}
这个之前写过了,其实和constructor意思是一样的,MDN上查到的资料是All objects will have a constructor property.  Objects created without the explicit use of a constructor function (i.e. the object and array literals) will have a constructor property that points to the Fundamenal Object constructor type for that object.

可以通过arr.constructor == Array来判断。

具体的constructor是什么意思,JS高程上有解释,以后有时间再研究。

还要一个最通用的是

Object.prototype.toString.call(value)
该方法返回的是一个字符串,比如下面的代码:

函数类型
Function fn(){console.log(“test”);}
Object.prototype.toString.call(fn);//”[object Function]”
日期类型
var date = new Date();
Object.prototype.toString.call(date);//”[object Date]”
数组类型
var arr = [1,2,3];
Object.prototype.toString.call(arr);//”[object Array]”
正则表达式
var reg = /[hbc]at/gi;
Object.prototype.toString.call(reg);//”[object RegExp]”
但是自定义类型无法识别




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值