js实现typeof
typeof 运算符的基本用法
JavaScript 的 typeof 运算符用于检测变量的数据类型,返回一个表示类型的字符串。以下是基本语法:
typeof operand
operand 可以是变量、对象或原始值。返回的结果是以下字符串之一:
"undefined"(未定义)"boolean"(布尔值)"number"(数字)"string"(字符串)"bigint"(大整数)"symbol"(符号)"object"(对象或null)"function"(函数)
实现自定义 typeof 函数
如果需要实现一个类似 typeof 的函数,可以通过 Object.prototype.toString 方法实现更精确的类型判断:
function customTypeof(value) {
return Object.prototype.toString.call(value).slice(8, -1).toLowerCase();
}
调用示例:

customTypeof(42); // "number"
customTypeof("hello"); // "string"
customTypeof(true); // "boolean"
customTypeof({}); // "object"
customTypeof([]); // "array"
customTypeof(null); // "null"
customTypeof(undefined); // "undefined"
customTypeof(() => {}); // "function"
customTypeof(Symbol()); // "symbol"
customTypeof(10n); // "bigint"
注意事项
typeof null 返回 "object" 是 JavaScript 的历史遗留问题。如果需要区分 null 和普通对象,可以使用以下方法:
function isNull(value) {
return value === null;
}
对于数组和对象的区分:

function isArray(value) {
return Array.isArray(value);
}
实际应用场景
-
检查变量是否已定义:
if (typeof variable === 'undefined') { // 变量未定义 } -
检查函数是否存在:
if (typeof myFunction === 'function') { myFunction(); } -
处理多种数据类型:
function processValue(value) { switch (typeof value) { case 'string': return value.toUpperCase(); case 'number': return value * 2; default: return value; } }






