数据类型判断

22 阅读1分钟

如何判断 JS 的数据类型?

作者:庸人自扰的庸人 链接:juejin.cn/post/717664… 来源:稀土掘金

  1. typeof

typeof可以区分除了Null类型以外的其他基本数据类型,以及从对象类型中识别出函数(function)。

其返回值有:numberstringbooleanundefinedsymbolbigintfunctionobject

其中, typeof null返回 "object"

如果要识别null,可直接使用===全等运算符来判断。

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

  1. instanceof

instanceof一般是用来判断引用数据类型,但不能正确判断基本数据类型,根据在原型链中查找判断当前数据的原型对象是否存在返回布尔类型。

1 instanceof Number; // false
true instanceof Boolean; // false
'str' instanceof String; // false
[] instanceof Array; // true
function(){} instanceof Function; // true
{} instanceof Object; // true
let date = new Date();
date instance of Date; // true
  1. Object.prototype.toString.call(x)

    Object.prototype.toString({}) // "[object Object]"
    Object.prototype.toString.call({}) // 同上结果,加上call也ok
    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(function () {}) // "[object Function]"
    Object.prototype.toString.call(null) //"[object Null]"
    Object.prototype.toString.call(undefined) //"[object Undefined]"
    Object.prototype.toString.call(/123/g) //"[object RegExp]"
    Object.prototype.toString.call(new Date()) //"[object Date]"
    Object.prototype.toString.call([]) //"[object Array]"
    Object.prototype.toString.call(document) //"[object HTMLDocument]"
    Object.prototype.toString.call(window) //"[object Window]"