2. JS 有哪些数据类型
总结
- 基础类型(7 种):
number,string,boolean,null,undefined,symbol,bigint - 引用类型(对象及其子类):
object,array,function,date,regexp,map,set等
判断方式推荐:
- 基础类型:使用
typeof - 引用类型:使用
instanceof或Object.prototype.toString.call()
✅ 最佳实践:使用
Object.prototype.toString.call(value)实现最通用的类型判断逻辑。
一、JavaScript 中的数据类型分类
JavaScript 的数据类型可以分为 基础类型(Primitive Types) 和 引用类型(Reference Types)。
1. 基础数据类型(Primitive Types)
| 类型 | 描述 |
|---|---|
number | 表示数字,包括整数、浮点数,如 42, 3.14 |
string | 表示字符串,如 "hello" |
boolean | 表示布尔值,只有 true 和 false |
null | 表示空值,常用于表示“无”或“空对象引用” |
undefined | 表示未定义的值,变量声明但未赋值时为 undefined |
symbol | 表示唯一的、不可变的值,用于对象属性的键 |
bigint | 表示任意精度的整数(ES2020 引入),如 123456789012345678901234567890n |
⚠️ 注意:
typeof null返回"object",这是一个历史遗留的 bug。
2. 引用数据类型(Reference Types)
引用类型是对象(object)的子类型,存储的是对值的引用(内存地址)。
| 类型 | 描述 |
|---|---|
object | 普通对象,如 { name: "Tom" } |
array | 数组对象,如 [1, 2, 3] |
function | 函数对象,如 function foo() {} |
date | 日期对象,如 new Date() |
regexp | 正则表达式对象,如 /^\d+/ |
map, set, weakmap, weakset | ES6 引入的集合类型 |
二、如何判断数据类型?
1. typeof 运算符
适用于判断基础类型(除 null 外):
typeof 42; // "number"
typeof "hello"; // "string"
typeof true; // "boolean"
typeof undefined; // "undefined"
typeof Symbol(); // "symbol"
typeof 123n; // "bigint"
typeof null; // "object" ❌(错误)
2. instanceof 运算符
用于判断引用类型:
[] instanceof Array; // true
{} instanceof Object; // true
function() {} instanceof Function; // true
new Date() instanceof Date; // true
3. Object.prototype.toString.call()
适用于判断所有类型,是最准确的方式:
Object.prototype.toString.call(42); // "[object Number]"
Object.prototype.toString.call("hello"); // "[object String]"
Object.prototype.toString.call(true); // "[object Boolean]"
Object.prototype.toString.call(null); // "[object Null]"
Object.prototype.toString.call(undefined); // "[object Undefined]"
Object.prototype.toString.call(Symbol()); // "[object Symbol]"
Object.prototype.toString.call(123n); // "[object BigInt]"
Object.prototype.toString.call([]); // "[object Array]"
Object.prototype.toString.call(new Date()); // "[object Date]"
Object.prototype.toString.call(function () {}); // "[object Function]"
三、常见误区与注意事项
| 问题 | 说明 |
|---|---|
typeof null === "object" | 历史 bug,应使用 === null 判断 |
typeof [1,2,3] === "object" | 无法区分数组和其他对象,应使用 Array.isArray() |
NaN 的类型是 number | typeof NaN === "number",但它是非数值的 |
function 是对象,但 typeof 返回 "function" | 特殊处理 |
