Skip to content

01. JavaScript 类型系统与判断方法解析

1. JavaScript 的基本数据类型

JavaScript 采用动态类型系统,包含以下 7 种基本类型(截至 ES2023):

  1. 原始类型

    • undefined:未定义值
    • null:空值
    • boolean:布尔值(true/false
    • number:数字(含 NaNInfinity
    • string:字符串
    • symbol(ES6+):唯一标识符
    • bigint(ES2020+):大整数
  2. 对象类型

    • object:包含数组、函数、日期等引用类型
    • function(typeof 特殊处理)
javascript
// 类型示例
console.log(typeof 42);                // "number"
console.log(typeof 9007199254740991n); // "bigint"
console.log(typeof Symbol('id'));      // "symbol"

2. 类型判断方法对比

1. typeof 运算符

  • 适用场景:基本类型快速判断
  • 特殊表现:
    javascript
    typeof null           // "object"(历史遗留问题)
    typeof []             // "object"
    typeof new Date()     // "object"
    typeof function() {}  // "function"

2. instanceof 运算符

  • 原理:检查原型链
  • 局限性:
    javascript
    [] instanceof Array      // true
    'str' instanceof String  // false(原始类型 vs 包装对象)

3. Object.prototype.toString

  • 最可靠的类型检测方法:
    javascript
    Object.prototype.toString.call([])        // "[object Array]"
    Object.prototype.toString.call(null)      // "[object Null]"
    Object.prototype.toString.call(undefined) // "[object Undefined]"

4. 专用检测方法

  • Array.isArray()
  • Number.isNaN() vs 全局 isNaN()

3. 类型判断注意事项

  1. Null 检测的特殊性

    javascript
    const isNull = val => val === null;
  2. 包装对象陷阱

    javascript
    typeof new String('test')  // "object"
    typeof String('test')      // "string"
  3. 跨窗口对象检测

    javascript
    // 不同 iframe 中的数组
    frameArray instanceof Array  // false
  4. 自定义对象识别

    javascript
    class MyClass {}
    const obj = new MyClass();
    console.log(obj instanceof MyClass);  // true

4. 通用类型判断函数实现

javascript
function getType(value) {
  const type = typeof value;
  if (type !== 'object') {
    return type;
  }

  // 处理 null
  if (value === null) {
    return 'null';
  }

  // 通过对象 toString 检测
  const typeStr = Object.prototype.toString.call(value);
  return typeStr.slice(8, -1).toLowerCase();
}

// 测试用例
console.log(getType([]));          // 'array'
console.log(getType(null));        // 'null'
console.log(getType(/regex/));     // 'regexp'
console.log(getType(42n));         // 'bigint'

5. 类型判断优化策略

  1. 组合检测方法

    javascript
    function isPlainObject(obj) {
      return Object.prototype.toString.call(obj) === '[object Object]' 
        && obj.constructor === Object;
    }
  2. 性能优化

  3. ES6+ 类型检测

    javascript
    const isSymbol = val => typeof val === 'symbol';
    const isBigInt = val => typeof val === 'bigint';

6. 特殊场景处理

  1. NaN 检测

    javascript
    function isRealNaN(val) {
      return Number.isNaN(val);
    }
  2. Promise 检测

    javascript
    function isPromise(obj) {
      return !!obj && typeof obj.then === 'function';
    }
  3. 浏览器环境检测

    javascript
    function isElement(node) {
      return node instanceof HTMLElement;
    }

掌握准确的类型判断需要理解 JavaScript 的类型系统特性,建议:

  1. 优先使用 Object.prototype.toString 进行对象类型判断
  2. 对基本类型使用 typeof 快速检测
  3. 特殊值(如 nullNaN)使用专用检测方法
  4. 注意包装对象和原始类型的差异