返回
Object.prototype.toString.call(obj)的奇妙用法
前端
2023-09-15 01:54:56
Object.prototype.toString.call(obj)的妙用
JavaScript中有一个鲜为人知的方法Object.prototype.toString.call(obj),它可以准确检测对象类型。这种方法可以用来检测各种数据类型,包括基本类型和复杂类型。
基本类型检测
使用Object.prototype.toString.call(obj)可以检测基本类型,包括:
- 字符串:"[object String]"
- 数字:"[object Number]"
- 布尔值:"[object Boolean]"
- undefined:"[object Undefined]"
- null:"[object Null]"
console.log(Object.prototype.toString.call("")); // "[object String]"
console.log(Object.prototype.toString.call(123)); // "[object Number]"
console.log(Object.prototype.toString.call(true)); // "[object Boolean]"
console.log(Object.prototype.toString.call(undefined)); // "[object Undefined]"
console.log(Object.prototype.toString.call(null)); // "[object Null]"
复杂类型检测
使用Object.prototype.toString.call(obj)还可以检测复杂类型,包括:
- 数组:"[object Array]"
- 对象:"[object Object]"
- 函数:"[object Function]"
console.log(Object.prototype.toString.call([])); // "[object Array]"
console.log(Object.prototype.toString.call({})); // "[object Object]"
console.log(Object.prototype.toString.call(function() {})); // "[object Function]"
原理
Object.prototype.toString.call(obj)方法实际上是调用了Object.prototype.toString()方法,然后将结果作为字符串返回。Object.prototype.toString()方法会根据对象的类型返回不同的字符串。
例如,对于一个字符串对象,Object.prototype.toString()方法会返回"[object String]"。对于一个数字对象,Object.prototype.toString()方法会返回"[object Number]"。以此类推。
案例
检测数据类型
Object.prototype.toString.call(obj)方法可以用来检测数据类型。这在一些情况下非常有用,例如:
- 当你想知道一个变量的类型时。
- 当你想判断一个值是否符合某种类型时。
- 当你想对不同类型的数据执行不同的操作时。
function getType(obj) {
return Object.prototype.toString.call(obj).slice(8, -1);
}
console.log(getType("")); // "String"
console.log(getType(123)); // "Number"
console.log(getType(true)); // "Boolean"
console.log(getType(undefined)); // "Undefined"
console.log(getType(null)); // "Null"
console.log(getType([])); // "Array"
console.log(getType({})); // "Object"
console.log(getType(function() {})); // "Function"
检查数据类型
Object.prototype.toString.call(obj)方法可以用来检查数据类型。这在一些情况下非常有用,例如:
- 当你想确保一个值符合某种类型时。
- 当你想对不同类型的数据执行不同的操作时。
function checkType(obj, type) {
return Object.prototype.toString.call(obj) === `[object ${type}]`;
}
console.log(checkType("", "String")); // true
console.log(checkType(123, "Number")); // true
console.log(checkType(true, "Boolean")); // true
console.log(checkType(undefined, "Undefined")); // true
console.log(checkType(null, "Null")); // true
console.log(checkType([], "Array")); // true
console.log(checkType({}, "Object")); // true
console.log(checkType(function() {}, "Function")); // true
结论
Object.prototype.toString.call(obj)是一个非常有用的方法,它可以用来检测和检查数据类型。这种方法在很多情况下都非常有用,例如:
- 调试代码时。
- 编写健壮的代码时。
- 编写可重用代码时。