使用 typeof 避免误判的核心做法是结合 object.prototype.tostring.call() 进行二次校验,因为 typeof null 会返回 'object',而数组、函数和正则表达式等类型在 typeof 下的表现也各不相同。具体操作时,先通过 typeof 快速排除基本类型,再对疑似对象类型的值调用 tostring 方法获取精确的类型标签,从而准确区分 null、array 和 function 等易混淆类型。

如何区分 null 和 Array
在处理数据时,开发者常需判断一个变量是否为空对象引用还是数组。由于 typeof null 的历史遗留 bug 返回 'object',而 typeof [] 也返回 'object',仅靠 typeof 无法区分二者。解决方法是利用 Object.prototype.toString.call(value),它会返回形如 '[object Null]' 或 '[object Array]' 的字符串,通过截取最后部分即可精准识别。

function getType(value) {
if (value === null) return 'null';
if (typeof value !== 'object') return typeof value;
const tag = Object.prototype.toString.call(value);
return tag.slice(8, -1).toLowerCase();
}
console.log(getType(null)); // 'null'
console.log(getType([])); // 'array'
console.log(getType({})); // 'object'
上述代码首先处理了 null 的特例,然后对非对象类型直接返回 typeof 结果,最后对对象类型使用 toString 提取类型名。运行结果显示 null 被正确识别为 'null',数组被识别为 'array',普通对象被识别为 'object'。
如何区分 Function 和其他对象
在 JavaScript 中,函数也是对象的一种,因此 typeof function() {} 返回 'function',而 typeof [] 返回 'object'。虽然 typeof 能区分函数和普通对象,但在某些场景下需要统一处理所有非基本类型。此时可以结合 instanceof 或 toString 来进一步细化。例如,使用 toString 可以明确区分 Function、RegExp 和 Date 等内置对象,因为它们各自的 toString 返回值不同。
一个基于源码的 OpenAI Agents SDK JavaScript 和 TypeScript 技术文档。涵盖了代理编排、工具、转接、追踪以及实际安装路径。

function isFunction(val) {
return typeof val === 'function';
}
function isRegExp(val) {
return Object.prototype.toString.call(val) === '[object RegExp]';
}
console.log(isFunction(() => {})); // true
console.log(isRegExp(/test/)); // true
console.log(isFunction([])); // false
这段代码展示了如何分别判断函数和正则表达式。对于函数,直接使用 typeof 是最简洁的方式;对于正则表达式,则必须使用 toString 方法,因为 typeof /test/ 返回 'object'。运行结果表明,函数和正则表达式都能被准确识别,而数组不会被误判为函数。
基于程序中某个输入、条件或结果的具体问题
当输入值为 undefined 时,typeof 的行为与其他类型有何不同?在实际编程中,typeof undefined 返回 'undefined',这与 null 不同,不会引发误判。然而,如果开发者试图通过 typeof value === 'object' && value !== null 来过滤掉 null,那么 undefined 会被包含在内,因为它不是 null 且 typeof 结果为 'undefined'(注意:typeof undefined 实际上是 'undefined',不是 'object')。因此,在判断对象类型时,无需特别处理 undefined,因为它不会被 typeof 误判为对象。但若使用 Object.prototype.toString.call(undefined),则会返回 '[object Undefined]',这提供了另一种精确判断的方式。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










