JavaScript 中的 typeof 运算符是用于获取特定变量的数据类型的一元运算符。它位于其单个操作数之前,该操作数可以是任何类型。它返回一个字符串值,该值指示其操作数的数据类型。JavaScript 包含原始数据类型和非原始数据类型。
JavaScript 数据类型中有七种原始或基本类型:数字、字符串、布尔值、undefined、null、symbol 和 bigint。还有一种称为 object 的复合数据类型。object 数据类型包含三种 sub 数据类型: Object、Array 和 Date。
语法
以下是 typeof 运算符的语法 −
我们可以按如下方式编写不带括号的操作数 -
参数
- operand − 它可以是表示对象或基元的值、变量或表达式。在 JavaScript 中,基元是不是对象且没有方法或属性的数据。
返回值
它返回表示操作数数据类型的字符串值。
typeof 运算符返回的数据类型
下面是 typeof 运算符的返回值列表。
类型 | typeof 返回的字符串 |
---|---|
Number | "number" |
String | "string" |
Boolean | "boolean" |
Object | "object" |
Function | "function" |
Undefined | "undefined" |
Null | "object" |
Symbol | "symbol" |
Bigint | "bigint" |
JavaScript 中有七种原始数据类型: number、string、boolean、bigint、undefined、null 和 symbol。typeof 运算符可用于识别这些原始数据类型或基本数据类型。
typeof 运算符返回除 null 之外的所有基元值的相同数据类型。它为 null 值返回 “object”。
对于 object、date 和 array,它返回 “object” 作为数据类型。
对于函数和类,它返回 “function” 作为数据类型。
让我们使用 typeof 运算符逐个识别这些数据类型。
JavaScript typeof 用于检查数字类型的运算符
在 JavaScript 中,数字类型表示数值。JavaScript 对所有数字使用浮点表示。JavaScript typeof 运算符为所有类型的数字(如整数、浮点、零、Infinity、NaN 等)返回 'number'。
例
下面的示例演示如何使用 typeof 运算符检查数字数据类型。
输出
number
Set the variable to different value and then try...
JavaScript typeof 运算符来检查字符串类型
字符串表示字符序列。typeof 运算符有助于识别字符串变量。JavaScript typeof 运算符为所有类型的字符串返回 “string”,例如空字符串、字符串、字符串、多行字符串等。
例
在下面的示例中,我们使用 typeof 运算符来检查字符串数据类型。
输出
Set the variable to different value and then try...
JavaScript typeof 运算符来检查布尔类型
布尔值表示 true 或 false。tyepof 操作数返回布尔变量的布尔值。
例
在下面的示例中,我们使用 typeof 运算符来检查布尔数据类型。
输出
Set the variable to different value and then try...
JavaScript typeof 运算符来检查符号类型
符号是在 ES6 中引入的,它提供了一种创建唯一标识符的方法。将 typeof 运算符与符号一起使用将返回 “symbol”。
例
在下面的示例中,我们使用 typeof 运算符来检查 Symbol 数据类型。
输出
Set the variable to different value and then try...
JavaScript typeof 运算符来检查 Undefined 和 Null
“undefined” 类型表示缺少值。“null” 类型表示没有任何对象值。当对 undefined 变量使用 typeof 运算符时,它将返回 'undefined'。令人惊讶的是,将 typeof 运算符与 null 一起使用也会返回 “object”,这是 JavaScript 中已知的怪癖。
请注意,typeof 运算符将对未声明的变量和已声明但未分配的变量返回 “undefined”。
例在下面的示例中,我们使用 typeof 运算符来检查 undefined 数据类型。
输出
Set the variable to different value and then try...
JavaScript typeof 运算符来检查对象类型
JavaScript typeof 运算符为所有类型的对象(如 JavaScript 对象、数组、日期、正则表达式等)返回 “object”。
例
在下面的示例中,我们使用 typeof 运算符来检查对象数据类型。
输出
Set the variable to different value and then try...
JavaScript typeof 运算符检查函数类型
函数是 JavaScript 中的一等公民。JavaScript typeof 运算符为所有类型的函数返回 “function”。有趣的是,它也为 classes 返回 “function”。
例
在下面的示例中,我们使用 typeof 运算符来检查函数数据类型。
输出
Set the variable to different value and then try...
JavaScript typeof 运算符检查 BigInt 类型
typeof 运算符为 BigInt 数字返回 “bigint”。BigInt 值是太大而无法由数字基元表示的数值。
实时开发中的 JavaScript typeof 运算符
例如,开发人员从 API 获取数据。如果只有一个字符串,则 API 返回字符串响应,对于多个字符串,API 返回字符串数组。在这个场景下,开发者需要检查响应的类型是 string 还是 array,如果是 array,则需要遍历 array 的每个 string。
例在下面的示例中,我们检查 'response' 变量的类型并相应地打印其值。
输出
JavaScript 数组和 typeof 运算符
数组尽管在 JavaScript 中是一种对象类型,但与 typeof 运算符具有不同的行为。
使用 typeof 运算符时,数组返回 “object”,因此对于精确的数组检测,通常最好使用 Array.isArray()。
例
输出
Set the variable to different value and then try..