首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

js中typeof的用法

typeof 是 JavaScript 中的一个一元操作符,用于检测变量的数据类型。它返回一个表示变量类型的字符串。typeof 可以应用于任何 JavaScript 变量或表达式。

基础概念

typeof 操作符的基本语法如下:

代码语言:txt
复制
typeof variable

或者

代码语言:txt
复制
typeof (expression)

返回值

typeof 返回以下几种类型的字符串:

  • "undefined" —— 如果变量未定义。
  • "boolean" —— 如果变量是布尔值。
  • "number" —— 如果变量是数字。
  • "string" —— 如果变量是字符串。
  • "bigint" —— 如果变量是 BigInt 类型。
  • "symbol" —— 如果变量是 Symbol 类型。
  • "object" —— 如果变量是对象或 null(这是一个历史遗留问题,null 被错误地认为是对象)。
  • "function" —— 如果变量是函数(在 JavaScript 中,函数也是对象的一种)。

示例代码

代码语言:txt
复制
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 在需要检查变量类型时非常有用,尤其是在编写通用函数或处理用户输入时。例如,你可能想要确保一个函数只接受特定类型的参数:

代码语言:txt
复制
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,你应该使用严格相等运算符:

代码语言:txt
复制
if (value === null) {
    // value 是 null
}

这样就可以避免将 null 错误地识别为对象。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券