jQuery中的类型判断原理及实现
//测试Chrome版本 40.0.2214.115 m
//测试版本 41.0.2272.118 (64-bit) mac
//如有错误欢迎指出
//javaScrpt基本数据类型 numeber,boolean,string这三种
//判断类型的有三种办法
//第一种 typeof
//有几种情况是判断不出来的,null,new Date()
//典型区别不开的,当然还有其它的一些也判断不出
var class2type={};
console.info(typeof(null));//object
console.info(typeof(undefined));
console.info(typeof(new Date()));//object 我要的是date类型
//第二种 constructor
//这种方法几乎都可以判断了,但是存在bug,这就要不得了
console.info({}.constructor===Object);
console.info({}.constructor==Object);
console.info(new Date().constructor===Date);
console.info(new Date().constructor==Date);
//但是null undefinde 无构造
//1也是没有的.可以转化为(1).constructor
//第三种 toString方法最好最实用
var toString={}.toString;//防止被篡改
//写一个判断数据类型的方法
var type=function(obj){
//如果为null
if(obj==null){
return obj+"";
}
return typeof obj=="object" || typeof obj=="function" ?toString.call(obj):typeof obj;
};
console.info(type(new Date()));//[object Date]
console.info(type(null));
console.info(type({}));
console.info(type(1));
//到此结束 相关推荐
九天银河技术 2020-11-11
zhangjie 2020-11-11
Crazyshark 2020-11-13
步知道 2020-10-27
李轮清 2020-09-15
85251846 2020-09-14
wangpaiyonghu 2020-06-28
jackalwb 2020-06-14
yhljxy 2020-06-14
myveer 2020-06-14
xiaobaif 2020-06-14
klarclm 2020-06-13
songshijiazuaa 2020-06-13
TMD咯MySQL 2020-06-12
archive 2020-06-12
清风徐来水波不兴 2020-06-09