JS 判断数据类型的三个方法

JavaScript的数据类型有 null、undefined、Number、String、Object、Boolean、Symbol,其中Symbol类型是在ES6新增的类型。其中Object类型又包括三个子类型,Function、 Array、Object(狭义)。

判断数据类型有三个方法。

typeof

1
2
3
4
5
6
7
8
9
10
11
12
13
var list = [1,2,3];
var obj = {name: 'Han'}
var fun = function () {}

typeof 1 // 'number'
typeof 'Han' // 'string'
typeof true // 'boolean'
typeof undefined // 'undefined'
typeof null // 'object'
typeof list // 'object'
typeof obj // 'object'
typeof fun // 'function'
typeof a // 'undefined'

通过以上例子可以看出 typeof判断数据类型的特点

  1. 无法准备判断数组和对象
  2. typeof null 的返回值为 “object”, 这是因为早期null就是属于”object”
  3. typeof 一个未定义的变量不会报错,而是返回 “undefined”
    typeof在大多数情况是适用的,如果想准备判断数组,可使用Array.isArray()进行判断。

instanceof

instanceof 方法只适用于判断Object类型的对象,基本类型的数据不适用。它的原理是检查右边的构造函数的prototype属性是否在左边实例的原型链上。

1
2
3
4
5
6
7
8
9
10
11
12
13
var list = [1,2,3];
var obj = {name: 'Han'}
var fun = function () {}

list instanceof Array // true
obj instanceof Object // true
fun instanceof Function // true
1 instanceof Number // false
'Han' instanceof String // false
true instanceof Boolean //false

list instanceof Object // true
fun instanceof Object // true

Object.prototype.toString.call()

这个方法可以准确返回判断对象的数据类型。

1
2
3
4
5
6
7
8
9
10
11
12
var list = [1,2,3];
var obj = {name: 'Han'}
var fun = function () {}

Object.prototype.toString.call(null) // "[object Null]"
Object.prototype.toString.call(undefined) // "[object Undefined]"
Object.prototype.toString.call(1) // "[object Number]"
Object.prototype.toString.call('1') // "[object String]"
Object.prototype.toString.call(true) // "[object Boolean]"
Object.prototype.toString.call(list) // "[object Array]"
Object.prototype.toString.call('Han') // "[object String]"
Object.prototype.toString.call(fun) // "[object Function]"

参考链接: https://wangdoc.com/javascript/types/index.html