ZetCode

JavaScript typeof 关键字

最后修改于 2025 年 4 月 16 日

在本文中,我们将展示如何使用 JavaScript 中的 typeof 运算符来检查数据类型。

typeof 关键字

typeof 运算符返回一个字符串,指示未计算操作数的类型。它对于 JavaScript 中的类型检查和调试非常有用。该运算符可以使用或不使用括号。

JavaScript 是一种动态类型语言,这意味着变量可以保存任何类型的值。typeof 运算符有助于确定变量当前包含的值的类型。

该运算符返回以下字符串之一:"undefined", "boolean", "number", "string", "bigint", "symbol", "function" 或 "object"。请注意,对于数组和 null,它返回 "object"。

typeof 的基本用法

以下示例演示了 typeof 运算符的基本用法。

main.js
console.log(typeof 42);          // "number"
console.log(typeof 'hello');     // "string"
console.log(typeof true);        // "boolean"
console.log(typeof undefined);   // "undefined"
console.log(typeof null);        // "object"

这显示了 typeof 返回各种基本值的类型。请注意,null 返回 "object",这是 JavaScript 中一个众所周知的怪癖。该运算符适用于字面量和变量。

$ node main.js
number
string
boolean
undefined
object

检查变量类型

typeof 经常用于检查变量的类型。

main.js
let age = 30;
let name = 'John';
let isActive = true;
let user = { id: 1 };
let colors = ['red', 'green'];

console.log(typeof age);      // "number"
console.log(typeof name);    // "string"
console.log(typeof isActive);// "boolean"
console.log(typeof user);    // "object"
console.log(typeof colors);   // "object"

此示例检查不同变量的类型。请注意,对象和数组都返回 "object"。要区分数组,请改用 Array.isArray()

$ node main.js
number
string
boolean
object
object

检查函数类型

函数具有来自 typeof 的特殊返回值。

main.js
function greet() {
    return 'Hello';
}

const arrowFunc = () => console.log('Hi');

console.log(typeof greet);       // "function"
console.log(typeof arrowFunc);   // "function"
console.log(typeof Math.max);    // "function"
console.log(typeof class {});    // "function"

所有函数类型在使用 typeof 时都返回 "function"。这包括常规函数、箭头函数、内置函数和类构造函数。函数是 JavaScript 中可调用的对象。

$ node main.js
function
function
function
function

检查未定义的变量

typeof 可以安全地用于未声明的变量。

main.js
let declaredButUndefined;
console.log(typeof declaredButUndefined);  // "undefined"
console.log(typeof nonExistentVariable);    // "undefined"

if (typeof nonExistentVariable === 'undefined') {
    console.log('Variable does not exist');
}

与其他操作不同,typeof 不会为未声明的变量抛出 ReferenceError。这使其在检查变量是否存在后再使用时非常有用。未声明和未定义的变量都返回 "undefined"。

$ node main.js
undefined
undefined
Variable does not exist

类型检查对象和数组

typeof 在检查对象和数组时存在局限性。

main.js
const obj = { a: 1 };
const arr = [1, 2, 3];
const date = new Date();
const regex = /pattern/;

console.log(typeof obj);    // "object"
console.log(typeof arr);    // "object"
console.log(typeof date);   // "object"
console.log(typeof regex);  // "object"

所有对象类型都返回 "object",这使得 typeof 无法区分不同的对象类型。对于更精确的检查,请使用 instanceof 或构造函数检查。

$ node main.js
object
object
object
object

使用运算符进行类型检查

typeof 可以与其他运算符结合使用进行类型检查。

main.js
function processValue(value) {
    if (typeof value === 'string') {
        return value.toUpperCase();
    } else if (typeof value === 'number') {
        return value * 2;
    } else if (typeof value === 'boolean') {
        return !value;
    }
    return 'Unsupported type';
}

console.log(processValue('hello'));  // "HELLO"
console.log(processValue(10));      // 20
console.log(processValue(true));    // false
console.log(processValue(null));    // "Unsupported type"

此示例展示了 typeof 的实际用途,以不同方式处理不同的类型。该函数根据其类型处理值,并为每种情况使用适当的操作。

$ node main.js
HELLO
20
false
Unsupported type

typeof 的边缘情况

在使用 typeof 时,需要注意一些边缘情况。

main.js
console.log(typeof NaN);            // "number"
console.log(typeof Infinity);       // "number"
console.log(typeof document.all);   // "undefined" (legacy)
console.log(typeof BigInt(10));    // "bigint"
console.log(typeof Symbol('id'));  // "symbol"

这些示例显示了一些特殊情况。NaN 在技术上是一个数字,而 document.all 是一个返回 "undefined" 的遗留情况。像 BigIntSymbol 这样的新类型有它们自己的类型字符串。

$ node main.js
number
number
undefined
bigint
symbol

来源

typeof - 语言参考

在本文中,我们演示了如何使用 typeof 运算符来检查 JavaScript 中的数据类型。

作者

我的名字是 Jan Bodnar,我是一个充满激情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直在撰写编程文章。迄今为止,我撰写了 1,400 多篇文章和 8 本电子书。我拥有超过十年的编程教学经验。

查看 所有 JavaScript 教程。