判断类型的几种方式

Object.prototype.toString()

如果是 Object,那么它本身就有 toString 的方法,直接调用就可以了。

/** `Object#toString` result references. */
const argsTag = "[object Arguments]"
const arrayTag = "[object Array]"
const boolTag = "[object Boolean]"
const dateTag = "[object Date]"
const errorTag = "[object Error]"
const mapTag = "[object Map]"
const numberTag = "[object Number]"
const objectTag = "[object Object]"
const regexpTag = "[object RegExp]"
const setTag = "[object Set]"
const stringTag = "[object String]"
const symbolTag = "[object Symbol]"
const weakMapTag = "[object WeakMap]"
 
const arrayBufferTag = "[object ArrayBuffer]"
const dataViewTag = "[object DataView]"
const float32Tag = "[object Float32Array]"
const float64Tag = "[object Float64Array]"
const int8Tag = "[object Int8Array]"
const int16Tag = "[object Int16Array]"
const int32Tag = "[object Int32Array]"
const uint8Tag = "[object Uint8Array]"
const uint8ClampedTag = "[object Uint8ClampedArray]"
const uint16Tag = "[object Uint16Array]"
const uint32Tag = "[object Uint32Array]"

来源 lodash

Typeof

需要注意的是对于 object、null 以及其他的任何对象,最后得到的结果都是 object
所以是没有办法区别 object,null 和其他对象的。

Instanceof

Constructor

什么时候应该选择什么样的方式

参考

判断 JS 数据类型的四种方法