JavaScript 判断数据类型

8/9/2021 前端JavaScript

# JavaScript 中数据类型

  • 值类型(基本类型):StringNumberBigIntBooleanNullUndefinedSymbol
  • 引用数据类型:ObjectArrayFunction

# 判断数据类型

假设有以下数据需要区分

let str = ''
let num = 0
let bi = 1n
let bool = true
let nul = null
let und = undefined
let sym = Symbol('1')
let obj = {}
let arr = []
let fuc = function() {}

function Person() {}
let person = new Person()

function Student() {}
Student.prototype = new Person()
let student = new Student()

判断的方法很多,按需使用:

# typeof

不能判断 NullObjectArray 和不同实例

typeof str // "string"
typeof num // "number"
typeof bi // "bigint"
typeof bool // "boolean"
typeof nul // "object"
typeof und // "undefined"
typeof sym // "symbol"
typeof obj // "object"
typeof arr // "object"
typeof fuc // "function"

typeof person // "object"
typeof student // "object"

# instanceof

不能判断 nullundefined、不是用 new 声明的基本类型和不同实例

str instanceof String // false
num instanceof Number // false
bi instanceof BigInt // false
bool instanceof Boolean // false
sym instanceof Symbol // false
obj instanceof Object // true
arr instanceof Array // true
fuc instanceof Function // true

let strNew = new String()
strNew instanceof String // true
let numNew = new Number()
numNew instanceof Number // true
let boolNew = new Boolean()
boolNew instanceof Boolean // true

person instanceof Person // true

student instanceof Student // true
student instanceof Person // true

# constructor

不能判断 nullundefined,并且它是不安全的,contructor 的指向可以被篡改。

str.constructor === String // true
num.constructor === Number // true
bi.constructor === BigInt // true
bool.constructor === Boolean // true
obj.constructor === Object // true
arr.constructor === Array // true
fuc.constructor === Function // true

function Person() {}
let person = new Person()
person.constructor === Person // true

student.constructor === Student // false
student.constructor === Person // true

# Object.prototype.toString.call

不能区分不同实例

Object.prototype.toString.call(str) // "[object String]"
Object.prototype.toString.call(num) // "[object Number]"
Object.prototype.toString.call(bi) // "[object BigInt]"
Object.prototype.toString.call(bool) // "[object Boolean]"
Object.prototype.toString.call(nul) // "[object Null]"
Object.prototype.toString.call(und) // "[object Undefined]"
Object.prototype.toString.call(sym) // "[object Symbol]"
Object.prototype.toString.call(obj) // "[object Object]"
Object.prototype.toString.call(arr) // "[object Array]"
Object.prototype.toString.call(fuc) // "[object Function]"

Object.prototype.toString.call(person) // "[object Object]"
Object.prototype.toString.call(student) // "[object Object]"