JS如何判断属性类型

JS基本类型有数字、布尔、字符串和对象类型。

typeof ""
"string"
typeof 1
"number"
typeof true
"boolean"
typeof /^$/
"object"
typeof Date
"function"
typeof new Date()
"object"
typeof {}
"object"
typeof []
"object"

可见除了基本类型string,number,boolean还有function,object
 

JS常用对象有几种:Number Array Boolean String Date Function RegExp Null Undefined

而声明属性只有 var, 所以当需要判断属性类型时, 会有一些麻烦。

如何判断属性类型呢? 在读jquery源码时,有这么一段

jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
	class2type[ "[object " + name + "]" ] = name.toLowerCase();
})

	type: function( obj ) {
		return obj == null ?
			String( obj ) :
			class2type[ toString.call(obj) ] || "object";
	}

实际上这个作用是

Object.prototype.toString.call(true);
"[object Boolean]"
Object.prototype.toString.call(1);
"[object Number]"
Object.prototype.toString.call("");
"[object String]"
Object.prototype.toString.call(function(){});
"[object Function]"
Object.prototype.toString.call([]);
"[object Array]"
Object.prototype.toString.call(new Date());
"[object Date]"
Object.prototype.toString.call(/^$/);
"[object RegExp]"
Object.prototype.toString.call({});
"[object Object]"

按照jquery的用法可以区分这常用的几种数据类型,非常方便。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值