封装一个通用方法:
function getType(tar){
const type = typeof tar;
if(type !== 'object') return type;
return Object.prototype.toString.call(tar).slice(8, -1).toLowerCase()
// Object.prototype.toString.call(tar).replace(/^\[object (\S+)\]$/, '$1').toLowerCase()
}
getType({}) // 'object'
getType(1) // 'number'
Object.prototype.toString详解
Object.prototype.toString.call('') // '[object String]'
Object.prototype.toString.call(null) // '[object Null]'
Object.prototype.toString.call(undefined) // '[object Undefined]'
Object.prototype.toString.call(1) // '[object Number]'
Object.prototype.toString.call(NaN) // '[object Number]'
Object.prototype.toString.call(false) // '[object Boolean]'
Object.prototype.toString.call(10n) // '[object BigInt]'
Object.prototype.toString.call(Symbol('')) // '[object Symbol]'
Object.prototype.toString.call({}) // '[object Object]'
Object.prototype.toString.call([]) // '[object Array]'
Object.prototype.toString.call(/s/g) // '[object RegExp]'
Object.prototype.toString.call(new Date()) // '[object Date]'
Object.prototype.toString.call(Math) // '[object Math]'
Object.prototype.toString.call(function(){}) // '[object Function]'
Object.prototype.toString.call(new Map()) // '[object Map]'
Object.prototype.toString.call(new Set()) // '[object Set]'
|