JavaScript 类型判断

//  1--
//  javascript 自带的 typeof 运算符不能很好的显示所有的类型;
//  比如 typeof null; typeof [1,2,3];
//  下面函数的基本原理是调用 Object.prototype 原型上的 toString 方法;
export function typeOf_(obj) {
  const 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 Undefined]': 'undefined',
    '[object Null]': 'null',
    '[object Object]': 'object',
    '[object Symbol]': 'symbol',
    '[object Error]': 'error',
  };
  return map[toString.call(obj)];
}
//  usage
const arr = [
  typeOf_(true),
  typeOf_(12.12),
  typeOf_('A'),
  typeOf_(typeOf_),
  typeOf_([]),
  typeOf_(new Date('2019-02-14')),
  typeOf_(/(\w{3})+/),
  typeOf_(),
  typeOf_(Object.prototype.__proto__),
  typeOf_(Object.create(null)),
  typeOf_(Symbol('A')),
  typeOf_(new Error('A')),
];
for (let i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}

单个判断方法

export function isBoolean(args) {
  return typeOf_(args) === 'boolean';
}
export function isNumber(args) {
  return typeOf_(args) === 'number';
}
export function isString(args) {
  return typeOf_(args) === 'string';
}
export function isArray(args) {
  return typeOf_(args) === 'array';
}
export function isDate(args) {
  return typeOf_(args) === 'date';
}
export function isRegExp(args) {
  return typeOf_(args) === 'regexp';
}
export function isUndefined(args) {
  return typeOf_(args) === 'undefined';
}
export function isNull(args) {
  return typeOf_(args) === 'null';
}
export function isObject(args) {
  return typeOf_(args) === 'object';
}
export function isSymbol(args) {
  return typeOf_(args) === 'symbol';
}
export function isError(args) {
  return typeOf_(args) === 'error';
}

你可能感兴趣的:(JavaScript 类型判断)