⭐️ 区别
typeof | instanceof | |
---|---|---|
作用 | 检测数据类型 | 检测对象之间的关联性 |
返回 | 小写字母字符串 | 布尔值 |
操作数 | 简单数据类型、函数或对象 | 左边必须是引用类型 右边必须是函数 |
操作数数量 | 1个 | 2个 |
typeof 检测数据类型
typeof
检测数据类型
简单数据类型:
undefined
null
boolean
number
string
symbol
bigint
后面两种为es6新增
复杂数据类型:
object
typeof undefined
'undefined'
typeof true
'boolean'
typeof 123
'number'
typeof NaN
'number'
typeof 'apple'
'string'
typeof function(){}
'function'
typeof Symbol
'function'
-------------------------------------------------------------
typeof []
'object'
typeof {}
'object'
typeof null
'object'
typeof new Date()
'object'
typeof 123333433333333333333n
'bigint'
typeof Symbol('a')
'symbol'
typeof
总结:返回一个小写字母类型的字符串,只需一个操作数,简单数据类型或者函数或者对象
instanceof 检测对象之间的关联性
instanceof
原理就是判断实例对象的__proto__
是否跟构造函数的prototype
相等
a = new Number(888)
Number {888}
a instanceof Number
true
c = new Array(5, 66, 7)
(3) [5, 66, 7]
c instanceof Array
true
888 instanceof Number
false