6、Javascript数据类型判断

1、运算符typeof

1 var arr = [new Object(),null, undefined, 1, "你好", true];
2         arr.forEach(function(item){
3             console.log(typeof item)
4         })
5             

打印结果如下:

 从打印结果来看:JavaScript的六种数据类型Undefined、Null、Boolean、Number、String、Object的结果分别为undefined、object、boolean、number、string、object

除此之外 Object 下还有很多细分的类型呐,如 Array、Function、Date、RegExp、Error 等。

1 function func(){}
2         var arr = [[1,2],func, new Error, /\1/, new Date()];
3         arr.forEach(function(item){
4             console.log(typeof item)
5         })

打印结果如下:

 

 由此可见,typeof无法判断object下的类型;那怎么判断一个变量是数组还是其它你的,我们继续往下看;

2、Object.prototype.toSting;

1 function func(){}
2         var arr = [[1,2],func, new Error, /\1/, new Date()];
3         arr.forEach(function(item){
4             console.log(Object.prototype.toString.call(item) )
5         })

打印结果:

 

 从打印结果可以得到我们需要的答案;

3、type函数封装

 1 // 第一版
 2 var classtype = {};
 3 
 4 // 生成classtype映射
 5 "Boolean Number String Function Array Date RegExp Object Error Null Undefined".split(" ").map(function(item, index) {
 6     classtype["[object " + item + "]"] = item.toLowerCase();
 7 })
 8 
 9 function type(obj) {
10     return typeof obj === "object" || typeof obj === "function" ?
11         classtype[Object.prototype.toString.call(obj)] || "object" :
12         typeof obj;
13 }

 

posted @ 2020-05-11 09:20  是假小发不是桂  阅读(191)  评论(0)    收藏  举报