当前位置:首页 > 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
分享给朋友:

相关文章

vue实现js休眠

vue实现js休眠

Vue 中实现 JavaScript 休眠 在 Vue 中实现 JavaScript 休眠通常需要使用异步方式,以避免阻塞主线程。以下是几种常见方法: 使用 setTimeout 和 Pro…

js 实现倒计时

js 实现倒计时

实现倒计时的基本方法 使用 JavaScript 实现倒计时可以通过 setInterval 或 setTimeout 结合日期计算来完成。以下是两种常见实现方式。 使用 setInterval 实…

js实现报表

js实现报表

使用JavaScript实现报表 在JavaScript中实现报表功能可以通过多种方式完成,常见的方法包括使用原生JavaScript、第三方库(如Chart.js、D3.js)或结合后端数据渲染。以…

js实现驼峰

js实现驼峰

实现驼峰命名的几种方法 使用正则表达式和字符串替换 通过正则表达式匹配字符串中的特定模式(如下划线或短横线),并将其后的字母转换为大写,同时移除分隔符。 function toCamelCase(s…

js实现菜单

js实现菜单

实现基本HTML结构 使用HTML创建菜单的基本框架,通常包含<ul>和<li>元素。示例结构如下: <ul id="menu"> <li><…

js图片轮播的实现

js图片轮播的实现

基础图片轮播实现 使用HTML、CSS和JavaScript实现一个简单的图片轮播效果。HTML部分定义轮播容器和图片,CSS负责样式和过渡效果,JavaScript处理逻辑。 <div cl…