分析
- 在前端中,能判断类型的无非几种
- 1 )typeof 只能判断值类型,其他就是 function 和 object
- 2 ) instanceof 需要两个参数判断,不是获取
- 3 )手动枚举各种类型
- 可能会忽略某些类型
- 如果新增了类型,则需要修改代码
- 这种方案不可取
- 4 )原生API
Object.prototype.toString.call(input)
input 是用户输入- 而非
input.toString()
这种不可行
测试 Object.prototype.toString.call
Object.prototype.toString.call(12)
// ‘[object Number]’Object.prototype.toString.call(NaN)
// ‘[object Number]’Object.prototype.toString.call(-Infinity)
// ‘[object Number]’Object.prototype.toString.call('abc')
// ‘[object String]’Object.prototype.toString.call([])
// ‘[object Array]’Object.prototype.toString.call({})
// ‘[object Object]’Object.prototype.toString.call(() => {})
// ‘[object Function]’Object.prototype.toString.call(new Set())
// ‘[object Set]’Object.prototype.toString.call(new WeakSet())
// ‘[object WeakSet]’Object.prototype.toString.call(new Map())
// ‘[object Map]’Object.prototype.toString.call(new WeakMap())
// ‘[object WeekMap]’Object.prototype.toString.call()
// ‘[object Undefined]’Object.prototype.toString.call(undefined)
// ‘[object Undefined]’Object.prototype.toString.call(null)
// ‘[object Null]’
基于以上测试,可看到可以获取具体的类型
代码实现
1 )编码
export function getType(input: any): string {
const orgType = Object.prototype.toString.call(input) // '[object String]'
const i = orgType.indexOf(' ')
const type = orgType.slice(i + 1, -1)
return type.toLowerCase() // 'string'
}
2 )测试
console.log(getType(1)) // number
console.log(getType(NaN)) // number
console.log(getType('ass')) // string
console.log(getType(null)) // null
console.log(getType(undefined)) // undefined
console.log(getType({})) // object
console.log(getType(() => {})) // function
console.log(getType(new WeakSet())) // weakset