typeof 对于原始类型来说,除了null 都可以显示争取的类型
typeof 1 // 'number'
typeof '1' // 'string'
typeof undefined // 'undefined'
typeof true // 'boolean'
typeof Symbol() // 'symbol'
复制代码
typeof 对于对象来说,除了函数都会显示Object,所以typeof 并不能准确的判断变量到底是什么类型
typeof [] //'Object'
typeof {} //'Object'
typeof cosnole.log //'function'
复制代码
如果我们想判断一个对象的正确类型,这时候可以考虑使用 instanceof,因为内部机制是通过原型链来判断的.
const person = function(){}
const p1 = new person()
p1.instanceof person //true
var str = 'hellwo word'
srr.instanceof String //fasle
var str1 = new String('hellow word')
str1.instanceof String //true
复制代码
对于原始类型来说,你想直接通过 instanceof 来判断类型是不行的