typeof 运算符在 JavaScript 中确实能够正确区分大多数原始值(Primitive values)。原始值包括 undefined、null、boolean、number、string 和 symbol(ES6 引入)。以下是每种原始值及其对应的 typeof 结果:
-
undefined类型:typeof undefined; // "undefined" -
null类型:typeof null; // "object" (值得注意的是,这是一个历史遗留的bug,实际上 null 不是对象类型) -
boolean类型:typeof true; // "boolean" typeof false; // "boolean" -
number类型:typeof 123; // "number" -
string类型:typeof 'hello'; // "string" -
symbol类型(ES6 新增):let sym = Symbol(); typeof sym; // "symbol"
另外,在 ES6 中还新增了 bigint 类型,也是一个原始值:
-
bigint类型:typeof 123n; // "bigint"
总的来说,typeof 在处理所有非 null 的原始值时都能够准确返回它们的类型。而对于 null,尽管返回的是 "object",但实际上应当将其视为一种特殊的原始值类型。因此,在实际开发中需要注意此特殊情况。
补充:
对于 {}(对象字面量)和 [](数组字面量),typeof 返回的类型都是 "object"
-
typeof {}返回"object",表示{}是一个对象实例,即使它没有显式指定为任何构造函数创建的对象。 -
typeof []也返回"object",虽然数组在 JavaScript 中是一种特殊的对象,但它在typeof运算下的类型表现与普通对象相同。 -
在 JavaScript 中,当你对一个函数进行
typeof操作时,它会返回"function":
function myFunction() {}
console.log(typeof myFunction); // 输出 "function"
这意味着 typeof 运算符能够正确识别并区分函数类型的值。即使是匿名函数表达式,typeof 也会返回 "function":
console.log(typeof function() {}); // 输出 "function"