js实现typeof
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 函数
原生 typeof 对 null 和数组的检测不够精确。可以通过以下方式实现更精确的类型检测:
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 可以检测函数,但更安全的方式是:

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),
typeof和Object.prototype.toString的结果一致 - 对于引用类型,
Object.prototype.toString能提供更具体的类型信息






