JavaScript 类型判断函数

216 阅读1分钟

背景

很多时候,我们需要在业务中判断数据的类型,每次都是很分散的,这个时候,我们可以封装一个函数,把所有的情况的包含进来

code

function getType(value) {
  // 判断数据是 null 的情况
  if (value === null) {
    return value + "";
  }

  // 判断数据是引用类型的情况
  if (typeof value === "object") {
    let valueClass = Object.prototype.toString.call(value),
      type = valueClass.split(" ")[1].split("");

    type.pop();

    return type.join("").toLowerCase();
  } else {
    // 判断数据是基本数据类型的情况和函数的情况
    return typeof value;
  }
}