ECMAScript有6种简单数据类型(也称为原始类型):Undefined、Null、Boolean、Number、String和Symbol。还有一种复杂数据类型叫Object(对象)。
Object是一种无序名值对的集合。
ECMAScript中不能定义自己的数据类型,所有值都可以用这7种数据类型之一来表示。
typeof操作符是用来检测任意变量的数据类型的一元运算符。
| 数据类型 | typeof返回值 | 含义 | 示例 |
|---|---|---|---|
| Undefined | "undefined" | 未定义 | typeof undefined |
| Null | "object"(历史遗留问题) | 空对象 | typeof null |
| Boolean | "boolean" | 布尔值 | typeof true |
| Number | "number" | 数值 | typeof 42, typeof NaN |
| BigInt | "bigint" | 任意精度整数 | typeof 9007199254740991n |
| String | "string" | 字符串 | typeof "hello" |
| Symbol | "symbol" | 符号 | typeof Symbol() |
| Function | "function" | 函数 | typeof function() {}, typeof class C {} |
| 其他对象 | "object" | 对象(而不是函数)或null | typeof {}, typeof [], typeof new Date() |
-
历史遗留问题:
typeof null返回"object"。这是因为在 JavaScript 早期实现中,用于标识类型的标签和对象相同。如果需要准确判断null,使用value === null。 -
无法区分对象子类型: 对于普通对象、数组、日期或正则表达式,
typeof统一返回"object"。要区分它们,可以借助更专业的方法:- 判断数组:使用
Array.isArray(value) - 判断其他内置对象:使用
Object.prototype.toString.call(value),它会返回如[object Array]、[object Date]等更精确的字符串。
- 判断数组:使用
console.log(Object.prototype.toString.call([])); // "[object Array]"
console.log(Object.prototype.toString.call(null)); // "[object Null]"
console.log(Object.prototype.toString.call(new Date())); // "[object Date]"
- 对未声明变量的容错性:
typeof检查一个未声明的变量不会抛出错误,而是返回"undefined"。这个特性有时可以用来安全地检查变量是否存在。但在let或const声明、赋值之前的"暂时性死区"内使用typeof会抛出ReferenceError。
if (typeof myVariable === 'undefined') {
console.log('myVariable 未定义或未初始化');
}