js typeof实现
typeof 的实现原理
JavaScript 中的 typeof 操作符用于检测变量的数据类型。其底层实现基于引擎内部的类型标签机制。在 ECMAScript 规范中,每个值都有一个关联的类型标签,typeof 通过读取这个标签返回对应的类型字符串。
基本数据类型检测
-
undefined: 变量未定义时返回
"undefined"typeof undefined; // "undefined" -
boolean: 布尔值返回
"boolean"typeof true; // "boolean" -
number: 数字类型返回
"number"(包括NaN和Infinity)typeof 42; // "number" typeof NaN; // "number" -
string: 字符串返回
"string"typeof "hello"; // "string" -
symbol: ES6 新增的 Symbol 类型返回
"symbol"typeof Symbol(); // "symbol" -
bigint: BigInt 类型返回
"bigint"typeof 9007199254740991n; // "bigint"
复杂数据类型检测
-
function: 函数对象返回
"function"typeof function() {}; // "function" -
object: 对象、数组、null 等返回
"object"typeof {}; // "object" typeof []; // "object" typeof null; // "object" (历史遗留问题)
手动实现 typeof
可以通过 Object.prototype.toString 实现更精确的类型检测:
function _typeof(obj) {
return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
}
_typeof(null); // "null"
_typeof([]); // "array"
注意事项
typeof 对 null 的检测结果是历史遗留问题,最初 JavaScript 使用 32 位系统存储值,其中低 3 位表示类型标签。object 的标签是 000,而 null 被表示为全零,因此被错误地归类为 object。
对于更精确的类型检测,建议结合使用 typeof 和 instanceof,或使用 Object.prototype.toString 方法。







