📅  最后修改于: 2023-12-03 15:01:22.143000             🧑  作者: Mango
typeof
在JavaScript中,有时候我们需要检测一个变量的类型,以便进行相应的操作。此时,我们可以使用 typeof
关键字来检测变量的类型。下面就让我们来看一看 typeof
的用法和返回值。
typeof 变量名
其中,变量名
可以是任何类型的变量,如:数字(Number
)、字符串(String
)、布尔(Boolean
)、Null、Undefined、对象(Object
)和函数(Function
)等。
typeof
返回一个字符串类型的值,表示变量的数据类型,可能的返回值有以下几种:
| 值 | 含义 |
| ---- | ---- |
| "undefined" | 变量未声明或未定义 |
| "boolean" | 变量是布尔类型 |
| "number" | 变量是数值类型 |
| "string" | 变量是字符串类型 |
| "object" | 变量是对象(但不是函数或null
) |
| "function" | 变量是函数类型 |
下面是一些使用 typeof
的示例。
let x = 123;
let result = typeof x;
console.log(result); // 输出 "number"
let x = "Hello, world!";
let result = typeof x;
console.log(result); // 输出 "string"
let x = true;
let result = typeof x;
console.log(result); // 输出 "boolean"
let x = {name: "Jane", age: 20};
let result = typeof x;
console.log(result); // 输出 "object"
let x = function() { console.log("Hello, world!"); };
let result = typeof x;
console.log(result); // 输出 "function"
let x;
let result = typeof x;
console.log(result); // 输出 "undefined"
typeof
是JavaScript中用于检测变量类型的关键字,返回值为一个字符串类型,表示变量的数据类型。在实际开发中,可以根据这个值来判断变量的类型,以便进行相应的操作。