typeof
是 JavaScript 中的一个一元操作符,用于检测一个变量的数据类型。它返回一个表示变量类型的字符串。typeof
可以应用于任何 JavaScript 表达式,包括变量、函数参数、对象属性等。
typeof
操作符返回的类型字符串有以下几种:
"undefined"
:未定义的值。"boolean"
:布尔值。"number"
:数字。"string"
:字符串。"bigint"
:大整数(ES2020 新增)。"symbol"
:符号(ES6 新增)。"function"
:函数(在 JavaScript 中,函数是一种特殊的对象)。"object"
:对象或者 null
(这是一个历史遗留问题,typeof null
返回 "object"
)。"any"
:TypeScript 中的类型(仅在 TypeScript 中有效)。使用 typeof
可以在运行时检查变量的类型,这对于编写健壮的代码和处理不同类型的输入非常有用。它可以帮助开发者避免类型相关的错误,并且可以在需要时执行类型转换。
let num = 123;
console.log(typeof num); // 输出: "number"
let str = "Hello, world!";
console.log(typeof str); // 输出: "string"
let bool = true;
console.log(typeof bool); // 输出: "boolean"
let obj = { key: "value" };
console.log(typeof obj); // 输出: "object"
let nul = null;
console.log(typeof nul); // 输出: "object" —— 注意这是一个历史遗留问题
let undef;
console.log(typeof undef); // 输出: "undefined"
function myFunc() {}
console.log(typeof myFunc); // 输出: "function"
let sym = Symbol("foo");
console.log(typeof sym); // 输出: "symbol"
let bigIntValue = BigInt(9007199254740991);
console.log(typeof bigIntValue); // 输出: "bigint"
问题:typeof null
返回 "object"
,这可能会导致混淆。
原因:这是 JavaScript 语言设计的一个历史遗留问题。在 JavaScript 最初的设计中,值是以 32 位存储的,其中低位的类型标签用于区分数据类型。null
被错误地表示为全零,这在类型标签中被解释为对象。
解决方法:使用严格相等运算符 ===
来检查 null
值。
let variable = null;
if (variable === null) {
console.log("The variable is null");
}
通过这种方式,可以准确地检测变量是否为 null
,而不会受到 typeof
操作符的限制。
领取专属 10元无门槛券
手把手带您无忧上云