js 数据类型判断总结

125 阅读2分钟

js类型判断的一般方法 typeof / instanceof,在实际的应用中存在不少槽点,比如 typeof(x) === 'object' , 你无法知道这个 x 究竟是 Object 是 Array 还是 Null,甚至还有可能是个字符串!

一 js的数据类型

  • 基本类型:Undefined、Null、Boolean、Number、String
  • 引用类型:Object
  • ES6 新增基本类型:BigInt、Symbol

二 常规判断

typeof 返回数据类型的字符串,有:undefined、boolean、number、string、bigint、symbol,及object (Null / Object)。

instanceof 返回值是 Boolean 值,用来判断一个对象是否是另一个对象的实例,检测的是原型。注意是对象类型的检测。

typeof

typeof(111)  // number
typeof(NaN) // number
typeof(Infinity) // number

typeof(true) // boolean
typeof('aa') // string
typeof(undefined) // undefined

typeof(null) // object
typeof([]) // object
typeof({}) // object
typeof(new Array()) // object

typeof(Array) // function
typeof(function(){}) // function

typeof(new String('aa')) // object

// es6 
typeof(Symbol('s')) // symbol
typeof(BigInt(3)) // bigint

由上可见:

  • 基本数据类型中 null 比较特殊,返回的是 object。typeof 根据数据机器码的后三位判断是何种数据类型,object 和 null的机器码后三位都是000。
  • 'aa' !== new String('aa'), 实例化后以对象的形式存在,而不再是基本数据类型。(可见“装箱与拆箱”一节)
  • 如果是一个函数,返回 function。

typeof.png

instanceof

{} instanceof Object // true

[] instanceof Array // true
[] instanceof Object // true

new Date() instanceof Date // true
new Date() instanceof Object // true

new String('aa') instanceof String // true
'aa' instanceof String // false

三 通用判断

/** 
 * 判断data的数据类型
 * 1. 返回值为具体类型的全字母小写:number boolean null array object...
 * 2. 注意:
 *   thrillTypeof(new Date()) === 'date'
 *   thrillTypeof(new Array()) === 'array'
 *   thrillTypeof(new RegExp()) === 'regexp'
 * 3. 如果函数不是js的内置对象,而是是自定义的, 比如 
 *   function Animal(){}
 *   thrillTypeof(new Animal()) === 'object'
 *   因此该方法不能正确判断非原生方法的实例,须用instanceof。 
 * 
 */
function thrillTypeof(data) {
    return Object.prototype.toString.call(data).substring(8, Object.prototype.toString.call(data).length - 1).toLowerCase();
}