跳到主要内容

js 判断数据类型

js 的类型判断有一点点复杂

js 的数据类型

  1. 基本类型:undefined,null,string,number,boolean,symbol(es6)
  2. 引用类型

判断类型方式

typeof

typeof 不能判断所有类型

typeof true // boolean
typeof undefined // undefined
typeof null // object
typeof '' // string
typeof 1 // number
typeof symbol(1) // symbol
typeof [] // object
typeof {} // object
typeof function () {} // function

null 和 array 会被判断为 object

instanceof

用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上, 无法判断基本数据类型

Object.prototype.toString.call()

可以判断所有数据类型,具体到某个对象

使用方式:

Object.prototype.toString.call(xxx)
({}).toString.call(xxx)
[].toString.call(xxx)

({}).toString.call('') // [object String]
......
({}).toString.call(new Date()) // [object Date]
({}).toString.call(Math) // [object Math]
({}).toString.call(/abc/ig) // [object Regexp]

判断数据类型

只判断基本数据类型和 function,array,object

const getType = (x) => {
let type = typeof x
if (type === 'object') {
if (x === null) {
type = 'null'
} else if (Array.isArray(x)) {
// 或 x instanceof Array === true
type = 'array'
}
}
return type
}

除基本数据类型外还判断属于哪一个具体对象

const getType = (x) => {
let type = typeof x
if (type === 'object') {
type = Object.prototype.toString.call(x).slice(8, -1).toLowerCase()
}
return type
}

* slice