JavaScript 的数据类型分为 原始类型(Primitive Types) 和 对象类型(Object Type),具体如下:
共有 7 种,值本身不可变,按值传递:
undefined
变量未初始化时的默认值。
例如:let a;
(a
为 undefined
)。
null
表示空值,通常用于显式清空变量。
注意:typeof null
返回 "object"
(历史遗留问题)。
boolean
布尔值:true
或 false
。
例如:let isDone = false;
。
number
数值类型(整数、浮点数、Infinity
、NaN
)。
例如:42
、3.14
、NaN
(非数字)。
string
字符串,用单引号或双引号包裹。
例如:"hello"
、'world'
。
symbol
(ES6 新增)
唯一且不可变的标识符,常用于对象属性的键。
例如:const key = Symbol('unique');
。
bigint
(ES2020 新增)
大整数,用于表示超过 Number
安全范围的整数。
例如:9007199254740991n
(以 n
结尾)。
一种复杂数据类型,按引用传递,可动态扩展属性:
object
普通对象:{}
、new Object()
。
数组:[]
、new Array()
。
函数:function() {}
、() => {}
(函数本质是对象)。
其他内置对象:Date
、RegExp
、Map
、Set
等。
typeof
操作符
typeof 42; // "number" typeof "hello"; // "string" typeof undefined; // "undefined" typeof null; // "object"(注意!) typeof {}; // "object" typeof []; // "object" typeof function(){}; // "function"
返回原始类型的名称(null
返回 "object"
)。
instanceof
操作符
javascript[] instanceof Array; // true{} instanceof Object; // true
检查对象是否为某个构造函数的实例。
Object.prototype.toString.call()
Object.prototype.toString.call(42); // "[object Number]" Object.prototype.toString.call(null); // "[object Null]" Object.prototype.toString.call([]); // "[object Array]" Object.prototype.toString.call({}); // "[object Object]"
精准判断任意数据类型(推荐)。
数组是对象:typeof []
返回 "object"
,需用 Array.isArray()
判断。
函数是对象:typeof function(){}
返回 "function"
,但本质是对象。
null
的陷阱:typeof null
返回 "object"
,需用严格相等判断:
javascriptlet a = null;a === null; // true
类型分类 | 具体类型 |
---|---|
原始类型 | undefined 、null 、boolean 、number 、string 、symbol 、bigint |
对象类型 | object (包括数组、函数、日期等) |
掌握数据类型是理解 JavaScript 的基础,避免因类型混淆导致的 Bug! 🚀