判断变量的类型工具方法,返回变量类型

Object.prototype.types = function () {
  let toString = Object.prototype.toString
  const map = {
    '[object Boolean]': 'boolean',
    '[object Number]': 'number',
    '[object String]': 'string',
    '[object Function]': 'function',
    '[object Array]': 'array',
    '[object Date]': 'date',
    '[object RegExp]': 'regExp',
    '[object Object]': 'object',
    '[object Arguments]': 'arguments',
    '[object Error]': 'error',
    '[object Window]': 'window',
    '[object HTMLDocument]': 'document',
    '[object Map]': 'map',
    '[object Set]': 'set',
    '[object WeakMap]': 'weakMap',
    '[object WeakSet]': 'weakSet'
  }
  let type = this instanceof Element ? 'element' : map[toString.call(this)]
  return type
}

使用方式:

由于undefined和null上没有方法,所以这两个数值只能通过 === 全等 确定了

猜你喜欢

转载自www.cnblogs.com/xzdm/p/11120365.html
今日推荐