怎么去判断一个数据属于哪个数据类型,这个是很常见的操作,我们一般都会想到typeof和instanceof这两个常见的方法,但有时候这两种方法并不能满足我们的需求。那让我们来看一下都有哪些可以判断数据类型的方法吧。
1.typeof
这个方法很常见,一般用来判断基本数据类型,如:string,number,boolean,symbol,bigint(es10新增一种基本数据类型bigint,详细介绍),undefined等。
typeof 目前能返回string,number,boolean,symbol,bigint,undefined,object,function这八种判断类型
typeof '123' string
typeof 1 number
typeof true boolean
typeof Symbol('1') symbol
typeof 111n bigint
typeof undefined undefined
typeof null object
typeof {
a:1,b:2} object
function c(){
console.log('123')}
typeof c function
其实我一直有个疑问,null既然属于基本数据类型,为什么用typeof返回的是object呢?解答如下:
js 在底层存储变量的时候,会在变量的机器码的低位1-3位存储其类型信息
000:对象
010:浮点数
100:字符串
110:布尔
1:整数
但是对于 undefined 和 null 来说,这两个值的信息存储是有点特殊的。
null:所有机器码均为0
undefined:用 −2^30 整数来表示
所以,typeof 在判断 null 的时候就出现问题了,由于 null 的所有机器码均为0,因此直接被当做了对象来看待。
2.instanceof
一般用来判断引用数据类型,如:Object,Function,Array,Date,RegExp等
/s/g instanceof RegExp true
new Date('2019/01/05') instanceof Date