通过调用 object.prototype.tostring.call(value) 可以准确判断 javascript 中各种数据的类型,该方法会返回形如 "[object type]" 的字符串。具体做法是将目标值作为 this 传入,利用内部 [[class]] 属性获取精确的类型标识,从而区分 null、undefined、数组、日期等内置对象。

如何区分基本类型与引用类型
对于基本类型和特殊值,toString 会直接返回对应的标准标签,例如数字返回 "[object Number]",布尔值返回 "[object Boolean]",而 null 和 undefined 分别返回 "[object Null]" 和 "[object Undefined]"。这种机制避免了直接使用 typeof 时出现的 null 被判定为 object 的历史遗留问题,确保了类型判断的严谨性。

function checkType(val) {
return Object.prototype.toString.call(val);
}
console.log(checkType(42)); // "[object Number]"
console.log(checkType(true)); // "[object Boolean]"
console.log(checkType(null)); // "[object Null]"
console.log(checkType(undefined)); // "[object Undefined]"
console.log(checkType("text")); // "[object String]"
console.log(checkType(Symbol())); // "[object Symbol]"
如何处理自定义对象与内置对象
对于内置对象如 Array、Date、RegExp 等,toString 会返回具体的类名,如 "[object Array]" 或 "[object Date]"。如果是自定义构造函数创建的实例,默认情况下会返回 "[object Object]",除非该对象重写了 Symbol.toStringTag 属性,否则无法通过此方法区分不同的自定义类。

const arr = [1, 2];
const date = new Date();
const regex = /test/;
const user = { name: 'Alice' };
class CustomClass {}
const instance = new CustomClass();
console.log(Object.prototype.toString.call(arr)); // "[object Array]"
console.log(Object.prototype.toString.call(date)); // "[object Date]"
console.log(Object.prototype.toString.call(regex)); // "[object RegExp]"
console.log(Object.prototype.toString.call(user)); // "[object Object]"
console.log(Object.prototype.toString.call(instance)); // "[object Object]"
当输入值为非对象且无原型链时会发生什么
当输入值为原始类型(如 number、string、boolean)时,Object.prototype.toString 会在内部将其包装为对应的对象实例,然后读取其 [[Class]] 属性。因此,即使传入的是原始值,也能正确返回对应的类型字符串,而不会抛出错误。这种行为使得该方法成为最可靠的类型检测手段之一,适用于所有可能的输入值。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











