1. typeof
typeof 判断基础类型,除null外均可正确判断。注意:NaN为number类型
typeof 1 // 'number'
typeof '1' // 'string'
typeof undefined // 'undefined'
typeof true // 'boolean'
typeof Symbol() // 'symbol'
typeof 1n // bigint
typeof NaN // number
typeof null // 'object' 错误
typeof 判断引用类型,除函数外均判断为'object'
typeof {} // 'object'
typeof [] // 'object'
typeof console.log // 'function'
2. instanceof
instanceof 通过原型链的方式来判断是否为构建函数的实例,常用于判断具体的对象类型。
const Person = function() {}
const p1 = new Person()
p1 instanceof Person // true
var str = 'test'
str instanceof String // false
var str1 = new String('test')
str1 instanceof String // true
str为原始类型,不可直接使用instanceof来判断类型。
[] instanceof Array // true
[] instanceof Object // true
console.log instanceof Function // true
console.log instanceof Object // true
3. Object.prototype.toString.call
此方法最为常用,能判断的类型最为完整。
Object.prototype.toString.call() // '[object Undefined]'
Object.prototype.toString.call(1) // '[object Number]'
Object.prototype.toString.call('1') // '[object String]'
Object.prototype.toString.call(undefined) // '[object Undefined]'
Object.prototype.toString.call(true) // '[object Boolean]'
Object.prototype.toString.call(Symbol()) // '[object Symbol]'
Object.prototype.toString.call(1n) // '[object BigInt]'
Object.prototype.toString.call(null) // '[object Null]'
Object.prototype.toString.call({}) // '[object Object]'
Object.prototype.toString.call(console.log) // '[object Function]'
Object.prototype.toString.call(/test/) // '[object RegExp]'
Object.prototype.toString.call(new Date()) // '[object Date]'
Object.prototype.toString.call(NaN) // '[object Number]'
可以进行封装
const getType =
(val) => Object.prototype.toString.call(val).slice(8, -1);
getType(1) // Number
4. 其他API
4.1 判断是否数组
Array.isArray([]) // true
4.2 isNaN
除 NaN 外均为false
isNaN(NaN) // true