在JavaScript中,获取参数的类型可以使用内置的 typeof
操作符。typeof
可以返回一个表示操作数类型的字符串。以下是一些基本数据类型及其对应的 typeof
返回值:
"undefined"
: 如果变量未定义或者是未初始化的变量"boolean"
: 如果变量是布尔值"string"
: 如果变量是字符串"number"
: 如果变量是数字"bigint"
: 如果变量是BigInt类型"symbol"
: 如果变量是Symbol类型"function"
: 如果变量是一个函数"object"
: 如果变量是对象或者 null
(注意,typeof null
会返回 "object"
,这是一个历史遗留问题)对于数组、日期、正则表达式等对象类型,typeof
也会返回 "object"
,因为它们都是对象的子类。如果需要更精确地区分这些类型,可以使用 Object.prototype.toString.call()
方法。
下面是一些示例代码,展示如何使用 typeof
和 Object.prototype.toString.call()
来获取参数的类型:
function getType(value) {
// 使用 typeof 判断基本类型
const type = typeof value;
if (type !== 'object') {
return type;
}
// 对于对象类型,使用 Object.prototype.toString.call 来判断
return Object.prototype.toString.call(value).slice(8, -1).toLowerCase();
}
console.log(getType(undefined)); // "undefined"
console.log(getType(true)); // "boolean"
console.log(getType("hello")); // "string"
console.log(getType(123)); // "number"
console.log(getType(123n)); // "bigint"
console.log(getType(Symbol('sym'))); // "symbol"
console.log(getType(function() {})); // "function"
console.log(getType(null)); // "null"
console.log(getType([])); // "array"
console.log(getType(new Date())); // "date"
console.log(getType(/regex/)); // "regexp"
在上面的代码中,getType
函数首先使用 typeof
来判断参数是否为基本类型。如果不是,它会使用 Object.prototype.toString.call()
来获取更精确的类型信息,并通过 .slice(8, -1).toLowerCase()
来格式化返回的字符串,以便得到更易读的类型名称。
这种方法的优点是可以准确地区分不同的对象类型,尤其是当需要区分数组、日期、正则表达式等复杂对象时。
应用场景包括:
如果你遇到了问题,比如 typeof
返回了意外的结果(例如 typeof null
返回 "object"
),那么可以使用上面提到的 getType
函数来获取更准确的类型信息。
领取专属 10元无门槛券
手把手带您无忧上云