四、JavaScript专题之类型判断(下)

上一篇文章中我们总结了类型判断的几种方式(typeof、Object.prototype.toString、Instanceof、isArray),这里我们写一个 type 函数来帮我们区分识别各种类型的值。

基础函数 type

首先,列出我们需要判断的常用类型(11 种):Boolean Number String Function Array Date RegExp Object Error Null Undefined;
我们的目标是:type(123) // 得到:number;
这里我们通过 typeof 和 Object.prototype.toString 来分别处理基础类型和引用类型,由于 null 和 undefined 会被 Object.prototype.toString 识别成 [object Object],所以它俩需要单独处理,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var class2type = {};
"Boolean Number String Function Array Date RegExp Object Error"
.split(" ")
.map((item) => {
class2type["[object " + item + "]"] = item.toLowerCase();
});
function type(obj) {
if (obj == null) {
return obj + "";
}
return typeof obj === "object" || typeof obj === "function"
? class2type[Object.prototype.toString.call(obj)] || "object" // 这里主要处理新增的类型:Set Map等等
: typeof obj;
}
type(123); // "number"
type(class2type); // "object"
type(type); // "function"
type(null); // "null"
type(/^\d+$/); // "regexp"
type(new Error()); // "error"
type(new Date()); // "date"

常用函数封装

有了 type 函数后,我们就可以直接对常用函数进行封装

1
2
3
4
5
6
7
8
9
10
11
12
function isFunction(obj) {
return type(obj) === "function";
}
function isDate(obj) {
return type(obj) === "date";
}
// 数组
var isArray =
Array.isArray ||
function (obj) {
return type(obj) === "array";
};

isEmptyObject

判断是否是空对象:

1
2
3
4
5
6
7
8
9
10
11
12
13
function isEmptyObject(obj) {
for (var name in obj) {
return false;
}
return true;
}
console.log(isEmptyObject({})); // true
console.log(isEmptyObject([])); // true
console.log(isEmptyObject(null)); // true
console.log(isEmptyObject(undefined)); // true
console.log(isEmptyObject(1)); // true
console.log(isEmptyObject("")); // true
console.log(isEmptyObject(true)); // true

isWindow

Window 对象作为客户端 JavaScript 的全局对象,它有一个 window 属性指向自身,基于这个特性来判断是否是 Window 对象。

1
2
3
function isWindow(obj) {
return obj != null && obj === obj.window;
}

isElement

判断是否是 DOM 节点。

1
2
3
function isElement(obj) {
return !!(obj && obj.nodeType === 1);
}

参考文献