JS 判断数据类型的四种方式
1. typeof 判断数据类型
- typeof 只能判断基本数据类型
- 判断复杂数据类型会返回 object
let arr = [1, 2, 3, 4, 5]
let obj = { a: 'jack', b: 'rose' }
let str = 'csdn'
let num = 1587
let bool = true
let und = undefined
let nl = null
let sy = Symbol('csdn')
let nums = NaN
function Demo() {}
console.log(typeof arr)
console.log(typeof obj)
console.log(typeof str)
console.log(typeof num)
console.log(typeof bool)
console.log(typeof Demo)
console.log(typeof und)
console.log(typeof nl)
console.log(typeof sy)
console.log(typeof nums)
2. instanceof 判断数据类型
- 语法 变量 a instanceof 数据类型 返回一个布尔值
- 只能判断对象是否存在于目标对象的原型链上,不能判断基本数据类型
let arr = [1, 2, 3, 4, 5]
let obj = { a: 'jack', b: 'rose' }
let str = 'csdn'
let num = 1587
let bool = true
let und = undefined
let nl = null
let sy = Symbol('csdn')
let nums = NaN
function Demo() {}
console.log(arr instanceof Array)
console.log(obj instanceof Object)
console.log(str instanceof String)
console.log(num instanceof Number)
console.log(bool instanceof Boolean)
console.log(und instanceof Object)
console.log(nl instanceof Object)
console.log(sy instanceof Symbol)
console.log(nums instanceof Number)
console.log(Demo instanceof Function)
3. constructor 判断数据类型
let arr = [1, 2, 3, 4, 5]
let obj = { a: 'jack', b: 'rose' }
let str = 'csdn'
let num = 1587
let bool = true
let und = undefined
let nl = null
let sy = Symbol('csdn')
let nums = NaN
function Demo() {}
let date = new Date()
let reg = /[hbc]at/gi
console.log(arr.constructor === Array)
console.log(obj.constructor === Object)
console.log(str.constructor === String)
console.log(num.constructor === Number)
console.log(bool.constructor === Boolean)
console.log(und.constructor === undefined)
console.log(nl.constructor === null)
console.log(sy.constructor === Symbol)
console.log(nm.constructor === Number)
console.log(Demo.constructor === Function)
console.log(date.constructor === Date)
console.log(reg.constructor === RegExp)
4. Object.prototype.toString.call 方法判断
- 最好的基本类型检测方式 Object.prototype.toString.call()
- 它可以区分 null string boolean number undefined array function object date math 数据类型
let arr = [1, 2, 3, 4, 5]
let obj = { a: 'jack', b: 'rose' }
let str = 'csdn'
let num = 1587
let bool = true
let und = undefined
let nl = null
let sy = Symbol('csdn')
let nums = NaN
function Demo() {}
let date = new Date()
let reg = /[hbc]at/gi
console.log(Object.prototype.toString.call(arr))
console.log(Object.prototype.toString.call(obj))
console.log(Object.prototype.toString.call(str))
console.log(Object.prototype.toString.call(num))
console.log(Object.prototype.toString.call(bool))
console.log(Object.prototype.toString.call(und))
console.log(Object.prototype.toString.call(nl))
console.log(Object.prototype.toString.call(sy))
console.log(Object.prototype.toString.call(nm))
console.log(Object.prototype.toString.call(Demo))
console.log(Object.prototype.toString.call(date))
console.log(Object.prototype.toString.call(reg))