当前位置:首页 > JavaScript

js实现typeof

2026-03-13 18:23:17JavaScript

typeof 的基本实现

JavaScript 的 typeof 操作符用于检测变量的数据类型。以下是原生 typeof 的行为示例:

console.log(typeof 42);          // "number"
console.log(typeof "hello");     // "string"
console.log(typeof true);        // "boolean"
console.log(typeof undefined);   // "undefined"
console.log(typeof null);        // "object" (历史遗留问题)
console.log(typeof {});          // "object"
console.log(typeof []);          // "object"
console.log(typeof function(){});// "function"

自定义 typeof 函数

原生 typeofnull 和数组的检测不够精确。可以通过以下方式实现更精确的类型检测:

function customTypeof(value) {
  if (value === null) {
    return 'null';
  }
  const baseType = typeof value;
  if (baseType !== 'object') {
    return baseType;
  }
  const toString = Object.prototype.toString;
  const tag = toString.call(value).slice(8, -1).toLowerCase();
  return tag;
}

使用 Object.prototype.toString

Object.prototype.toString 方法可以提供更精确的类型信息:

const toString = Object.prototype.toString;
console.log(toString.call(42));         // "[object Number]"
console.log(toString.call("hello"));    // "[object String]"
console.log(toString.call(true));       // "[object Boolean]"
console.log(toString.call(null));       // "[object Null]"
console.log(toString.call(undefined));  // "[object Undefined]"
console.log(toString.call({}));        // "[object Object]"
console.log(toString.call([]));        // "[object Array]"
console.log(toString.call(function(){}));// "[object Function]"

区分数组和对象

原生 typeof 无法区分数组和普通对象,可以通过以下方式区分:

function isArray(value) {
  return Array.isArray(value);
  // 或者
  return Object.prototype.toString.call(value) === '[object Array]';
}

检测函数类型

虽然 typeof 可以检测函数,但更安全的方式是:

js实现typeof

function isFunction(value) {
  return typeof value === 'function';
  // 或者
  return Object.prototype.toString.call(value) === '[object Function]';
}

注意事项

  • typeof null 返回 "object" 是 JavaScript 的历史遗留问题
  • 使用 Object.prototype.toString 方法可以获得更精确的类型信息
  • 对于原始类型(number, string, boolean),typeofObject.prototype.toString 的结果一致
  • 对于引用类型,Object.prototype.toString 能提供更具体的类型信息

标签: jstypeof
分享给朋友:

相关文章

js实现分页

js实现分页

分页的基本实现思路 在JavaScript中实现分页功能通常需要结合前端和后端逻辑。前端负责渲染分页控件和处理用户交互,后端负责提供分页数据。 前端分页实现 纯前端分页适用于数据量较小的情况,可以直…

js树实现

js树实现

树的基本概念 树是一种非线性的数据结构,由节点和边组成。每个节点包含一个值和指向子节点的引用。树的顶部节点称为根节点,没有子节点的节点称为叶节点。 树的实现方式 在JavaScript中,树可以通过…

链表实现js

链表实现js

链表的基本概念 链表是一种线性数据结构,由一系列节点组成,每个节点包含数据和一个指向下一个节点的指针(单向链表)或两个指针(双向链表)。与数组不同,链表在内存中非连续存储,插入和删除操作更高效,但随机…

js实现正交

js实现正交

正交的概念 正交在数学和计算机科学中通常指两个向量垂直或线性无关。在编程中,正交性常被用于设计模块化、低耦合的系统。 向量正交判断 判断两个向量是否正交可以通过点积是否为0来实现: functio…

js实现显示隐藏

js实现显示隐藏

显示隐藏的实现方法 在JavaScript中,实现元素的显示和隐藏可以通过多种方式完成。以下是几种常见的方法: 修改CSS的display属性 通过改变元素的display属性可以在none(隐藏)…

js sort 实现

js sort 实现

数组排序基础方法 JavaScript 数组的 sort() 方法默认按照字符串 Unicode 码点顺序排序。直接调用时会将元素转为字符串再比较: const arr = [10, 2, 5, 1…