上一篇文章中我们总结了类型判断的几种方式(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" : typeof obj; } type(123); type(class2type); type(type); type(null); type(/^\d+$/); type(new Error()); type(new 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({})); console.log(isEmptyObject([])); console.log(isEmptyObject(null)); console.log(isEmptyObject(undefined)); console.log(isEmptyObject(1)); console.log(isEmptyObject("")); console.log(isEmptyObject(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); }
|
参考文献