typeof
是 JavaScript 中的一个一元操作符,用于检测变量的数据类型。它返回一个表示变量类型的字符串。typeof
可以应用于任何 JavaScript 变量或表达式。
typeof
操作符的基本语法如下:
typeof variable
或者
typeof (expression)
typeof
返回以下几种类型的字符串:
"undefined"
—— 如果变量未定义。"boolean"
—— 如果变量是布尔值。"number"
—— 如果变量是数字。"string"
—— 如果变量是字符串。"bigint"
—— 如果变量是 BigInt 类型。"symbol"
—— 如果变量是 Symbol 类型。"object"
—— 如果变量是对象或 null
(这是一个历史遗留问题,null
被错误地认为是对象)。"function"
—— 如果变量是函数(在 JavaScript 中,函数也是对象的一种)。console.log(typeof undefined); // "undefined"
console.log(typeof true); // "boolean"
console.log(typeof 123); // "number"
console.log(typeof "hello"); // "string"
console.log(typeof 123n); // "bigint"
console.log(typeof Symbol()); // "symbol"
console.log(typeof null); // "object"(注意这是一个历史遗留问题)
console.log(typeof {}); // "object"
console.log(typeof []); // "object"
console.log(typeof function(){}); // "function"
typeof
在需要检查变量类型时非常有用,尤其是在编写通用函数或处理用户输入时。例如,你可能想要确保一个函数只接受特定类型的参数:
function addNumbers(a, b) {
if (typeof a !== 'number' || typeof b !== 'number') {
throw new TypeError('Both arguments must be numbers');
}
return a + b;
}
typeof null
返回 "object"
,这是一个已知的问题,因为 null
实际上是一个原始值,而不是对象。typeof
对于区分数组和普通对象是无能为力的,因为它们都返回 "object"
。如果需要区分数组,可以使用 Array.isArray()
方法。typeof null
的问题由于 typeof null
返回 "object"
,如果你需要准确地检查 null
,你应该使用严格相等运算符:
if (value === null) {
// value 是 null
}
这样就可以避免将 null
错误地识别为对象。
领取专属 10元无门槛券
手把手带您无忧上云