JS类型判断

104 阅读1分钟

Talk is cheap, show me the code

let class2Type = {}
let types = [
  'Boolean', 'Number', 'String', 'Object',
  'Function', 'Array', 'Date', 'RegExp'
]
for (let type of types) class2Type[`[object ${type}]`] = type.toLowerCase()

function type(obj) {
  if (obj == null) return obj + '' // undefine、null
  
  if (typeof obj == 'object' || typeof obj == 'function') return class2Type[Object.prototype.toString.call(obj)]
  return typeof obj
}

参考

1.JS类型判断上

2.JS类型判断下