fe-weekly-questions icon indicating copy to clipboard operation
fe-weekly-questions copied to clipboard

如何封装一个 javascript 的类型判断函数?

Open LuckyWinty opened this issue 4 years ago • 2 comments

LuckyWinty avatar Nov 08 '20 18:11 LuckyWinty

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
  }
}

LuckyWinty avatar Nov 08 '20 18:11 LuckyWinty

处理那一块建议换成 return Object.prototype.toString.call(value).slice(8,-1)

AdamZero avatar Mar 03 '21 09:03 AdamZero