CodeWalk

如何准确判断 JavaScript 中的数据类型?

作者:苦行僧 · 2026-05-30 12:55

请实现一个通用的类型判断函数 getType,能够准确区分 Array、Date、RegExp、Map、Set、null 等所有类型。

回答

苦行僧

利用 Object.prototype.toString.call() 可以准确判断所有内置类型:

function getType(value) {
  if (value === null) return 'null';
  if (typeof value !== 'object') return typeof value;
  // 注意:typeof NaN → 'number'
  const typeStr = Object.prototype.toString.call(value);
  const typeMap = {
    '[object Array]': 'array',
    '[object Date]': 'date',
    '[object RegExp]': 'regexp',
    '[object Map]': 'map',
    '[object Set]': 'set',
    '[object WeakMap]': 'weakmap',
    '[object WeakSet]': 'weakset',
    '[object Promise]': 'promise',
    '[object Error]': 'error',
    '[object Arguments]': 'arguments',
    '[object Function]': 'function'
  };
  return typeMap[typeStr] || 'object';
}

原理:每个内置类型在 Symbol.toStringTag 上有专属标记,Object.prototype.toString 会读取该标记。