javascript数据类型判断

163 阅读1分钟

数据类型

  • 7种原始类型,使用typeof运算符检查

const name = 'lili'; typeof name === "string" // true
原始类型检查类型
undefinedundefined
nullobject
Booleanboolean
Stringstring
Numbernumber
BigIntbigint
Symbolsymbol可以表示任意精度格式的整数
  • Object

任何从Object派生出来的结构类型(new Object、new Array、new Map、new Set、new WeakMap、new WeakSet、new Date、function,和几乎所有通过new keyword创建的东西),使用typeof得到的总会是“object”

typeof instance === "object" // true

检查Object种类的合适方法是使用 instanceof 关键字,但即使这样也会存在误差

对象类型检查方式
new Objectinstance instanceof Object // true
new ArrayArray.isArray(instance) // trueinstance instanceof Array && instance.constructor == Array
functionArray.isArray(instance) // trueinstance instanceof Function && instance.constructor == Function
... ...

类型检查通用方法

  1. Object.prototype.toString.call(instance)

注意:必须通过 call 或 apply 来调用,而不能直接调用 toString

从原型链的角度讲,所有对象的原型链最终都指向了 Object, 按照JS变量查找规则,其他对象应该也可以直接访问到 Object 的 toString方法,而事实上,大部分的对象都实现了自身的 toString 方法,这样就可能会导致 Object 的 toString 被终止查找,因此要用 call或apply 来强制调用Object 的 toString 方法。

a = 'lili' Object.prototype.toString.call(a) // "[object String]" 

各种类型如下: 
String"[object String]" 
Number(包含NaN) → "[object Number]" 
Boolean"[object Boolean]" 
undefined"[object Undefined]" 
Null"[object Null]" 
Symbol"[object Symbol]" 
new Object"[object Object]" 
new Date"[object Date]" 
new Array"[object Array]" 
Function"[object Function]" 
  1. constructor 方法
a = 'lili' a.constructor == String // true

本篇文章纯属个人理解,大家看完觉得有所收获或者有任何高见,欢迎留言点赞!后续会不定时更新~