JavaScript / TypeScript / 系统课时
使用 typeof 判断类型
使用 typeof 判断类型
typeof 是 JavaScript 中最常用的类型检测运算符,可以快速判断变量的数据类型。本节将学习它的返回结果、适用场景以及开发中经常遇到的 null 判断陷阱。
学习目标
- 掌握
typeof支持的数据类型判断方式。 - 理解
typeof null返回object的特殊情况。 - 能在实际代码中正确选择类型判断方案。
理解 typeof 的基本规则
typeof 会返回一个字符串,用于描述操作数的数据类型。它适合判断基础类型,例如字符串、数字、布尔值、函数和未定义值。
js
const name = "JavaScript";
const count = 10;
const enabled = true;
const callback = function () {};
let value;
console.log(typeof name);
console.log(typeof count);
console.log(typeof enabled);
console.log(typeof callback);
console.log(typeof value);预期输出
text
string
number
boolean
function
undefined常见返回值包括:
| 数据类型 | typeof 返回值 |
|---|---|
| 字符串 | string |
| 数字 | number |
| 布尔值 | boolean |
| 未定义 | undefined |
| 函数 | function |
| 对象、数组、null | object |
处理 typeof null 的特殊情况
虽然 null 表示空值,但执行 typeof null 时会得到 object。
js
const data = null;
console.log(typeof data);预期输出
text
object因此不能通过 typeof 判断变量是否为 null。正确方式是使用严格比较:
js
const data = null;
if (data === null) {
console.log("empty value");
}预期输出
text
empty value使用 typeof 的正确场景
typeof 特别适合处理变量可能不存在的情况,因为访问未声明变量时,直接使用变量会抛出错误,而 typeof 可以安全检查。
js
if (typeof optionalFeature !== "undefined") {
console.log("feature exists");
}预期输出
text
feature exists当变量不存在时,typeof optionalFeature 不会触发 ReferenceError,这也是它早期常用于兼容不同运行环境的重要原因。
什么时候不要使用 typeof
如果需要精确区分对象、数组、日期等引用类型,typeof 的信息不足。
js
const list = [];
const date = new Date();
console.log(typeof list);
console.log(typeof date);预期输出
text
object
object此时应该结合其他方法判断,例如使用 Array.isArray() 判断数组,或使用 instanceof 判断对象实例。
js
const list = [];
console.log(Array.isArray(list));预期输出
text
truetypeof 的定位是快速判断基础类型和安全检查变量存在性,而不是完整的类型系统。实际开发中,应根据需要组合使用严格比较、Array.isArray() 和其他检测方式。
按自己的节奏,确认真正理解。