JS 基于 toString 的通用类型判断,可判断原始类型跟引用类型
基于 toString 的通用类型判断,可判断原始类型跟引用类型
// 类型判断
function myTypeof(o){
const s = Object.prototype.toString.call(o);
return s.match(/\[object (.*?)]/)[1].toLowerCase();
}
myTypeof({}) // 'object'
myTypeof([]) // 'array'
myTypeof(123) // 'number'
myTypeof('123') // 'string'
myTypeof(null) // 'null'
myTypeof(NaN) // 'number'
myTypeof(Symbol(1)) // 'symbol'
myTypeof(undefined) // 'undefined'
myTypeof(true) // 'boolean'