JS类型判断

7/18/2022 js

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类型判断上 (opens new window)

2.JS类型判断下 (opens new window)

    爱自己,
    是终身浪漫的开始。
    红莲华
    x
    loading...