一、typeof
typeof
操作符返回一个字符串,表示未经计算的操作数的类型
使用方法如下:
typeof 1 // 'number'
typeof '1' // 'string'
typeof undefined // 'undefined'
typeof true // 'boolean'
typeof Symbol() // 'symbol'
typeof null // 'object'
typeof [] // 'object'
typeof {} // 'object'
typeof ()=>{} // 'function'
二、instanceof
instanceof
运算符用于检测构造函数的 prototype
属性是否出现在某个实例对象的原型链上
// 定义构建函数
let Car = function () {}
let benz = new Car()
benz instanceof Car // true
let car = new String('xxx')
car instanceof String // true
let str = 'xxx'
str instanceof String // false
三、区别
typeof
与instanceof
都是判断数据类型的方法,区别如下:
-
typeof
会返回一个变量的基本类型,instanceof
返回的是一个布尔值 -
instanceof
可以准确地判断复杂引用数据类型,但是不能正确判断基础数据类型 -
而
typeof
也存在弊端,它虽然可以判断基础数据类型(null
除外),但是引用数据类型中,除了function
类型以外,其他的也无法判断
可以看到,上述两种方法都有弊端,并不能满足所有场景的需求,如果需要通用检测数据类型,可以封装一个方法采用Object.prototype.toString
,调用该方法,使用replaced的方法改造一下返回的“[object Xxx]”
的字符串,返回一个Xxx的字符串.
如下
const myType= (types) =>{
const type = Object.prototype.toString.call(types).replace(/^\[object (\S+)\]$/, '$1')
console.log(type)
}
myType(null) //Null