获取数据的详细类型

50 阅读1分钟

基础使用typeof

在平常中使用typeof则可以判断所有的值类型, 引用类型, 而若是需要实现一个方法获取数据的详细类型的话,用typeof则不足够

方法实现Object.protype.toString

通过对象原型上的toString方法我们可以获得到所有数据的类型

// 获取数据的详细类型
export function typeOfData(x: any): String {
  const dataType = Object.prototype.toString.call(x)
  const spaceIndex = dataType.indexOf(' ')
  const type = dataType.slice(spaceIndex + 1, dataType.length - 1)
  return type.toLowerCase()
}