js实现typeof
typeof 运算符的基本用法
在 JavaScript 中,typeof 是一个一元运算符,用于返回一个表示操作数类型的字符串。以下是基本语法和常见类型的返回值:
typeof operand
常见返回值:

"number":数值类型(包括NaN)。"string":字符串类型。"boolean":布尔类型。"undefined":未定义的变量或值。"object":对象或null(历史遗留问题)。"function":函数类型。"symbol":Symbol 类型(ES6 新增)。
实现自定义 typeof 函数
由于原生 typeof 对 null 和数组的检测不够精确,可以通过以下方式实现更精确的类型检测:

function customTypeof(value) {
if (value === null) {
return "null";
}
const baseType = typeof value;
if (baseType !== "object") {
return baseType;
}
const objectType = Object.prototype.toString.call(value).slice(8, -1).toLowerCase();
return objectType;
}
处理特殊情况的示例
针对 null、数组和内置对象的检测:
console.log(customTypeof(null)); // "null"
console.log(customTypeof([])); // "array"
console.log(customTypeof(new Date())); // "date"
console.log(customTypeof(/regex/)); // "regexp"
使用 Object.prototype.toString 的底层原理
Object.prototype.toString 方法会返回 [object Type] 格式的字符串,其中 Type 是对象的内部类型:
Object.prototype.toString.call(42); // "[object Number]"
Object.prototype.toString.call("hello"); // "[object String]"
Object.prototype.toString.call(true); // "[object Boolean]"
注意事项
- 原生
typeof对函数返回"function",但函数本质是可调用的对象。 - 使用
instanceof可以检测对象的构造函数链。 - 现代 JavaScript 可以使用
Symbol.toStringTag自定义对象的类型标签。






