第一种:用 typeof xx 和 Object.prototype.toString.call(xx) 来判断
function type(obj) {
return typeof obj === 'object' ? Object.prototype.toString.call(obj).slice(8, -1).toLowerCase() : typeof obj
}
验证
console.log(type({})) // object
console.log(type(1)) // number
第二种:用 typeof xx 和 Array.isArray() 来判断
function type(obj) {
if (Array.isArray(obj)) return 'array'
if (obj === null) return 'null'
return typeof obj
}
验证
console.log(type({})) // object
console.log(type([])) // array
console.log(type(null)) // null
console.log(type(1)) // number
console.log(type(function () {})) // function