抄下jQ的代码,封装一个判断数据类型的函数

66 阅读1分钟
/**
 * 检测变量类型
 * @param {*} obj 需要检测类型的变量
 * @returns [string|number|boolean|null|symbol|bigint|object|array|function|date|regexp|error]
 */
function toType(obj) {
  var class2type = {},
    toString = class2type.toString;
  "Boolean Number String Function Array Date RegExp Object Error".split(' ').forEach(type => {
    class2type["[object " + type + "]"] = type.toLowerCase();
  })
  if(obj === null) {
    return "null";
  }
  return /^(object|function)$/.test(typeof obj) ? (class2type[toString.call(obj)] || "object") : typeof obj;
}
class R {}
console.log(1, toType(true));
console.log(2, toType(1));
console.log(3, toType(""));
console.log(4, toType(function() {}));
console.log(5, toType([]));
console.log(6, toType({}));
console.log(7, toType(/1/));
console.log(8, toType(new Error));
console.log(9, toType(new Date));
console.log(10, toType(new RegExp));
console.log(11, toType(new String("")));
console.log(12, toType(new Boolean()));
console.log(13, toType(null));
console.log(14, toType(new R));
console.log(15, toType(12n));
console.log(16, toType(Symbol(24)));

image.png