JavaScript中的数据类型主要分为两大类:基本数据类型和引用数据类型。基本数据类型包括:String(字符串)、Number(数字)、Boolean(布尔值)、Null(空值)、Undefined(未定义)、Symbol(唯一值)和bigInt(大整数值)。而引用数据类型则有:Object(对象)、Date(日期)、Function(函数)和Array(数组)。
1.
2.
3.
JavaScript 数据类型分类
1. 原始类型 (Primitive Types)
| 类型 | 说明 | 示例 |
|---|---|---|
undefined |
未赋值的默认类型 | let a; |
null |
空值 | let b = null; |
boolean |
布尔值 | true / false |
number |
整数/浮点数/特殊数值 | 42 / 3.14 / NaN |
bigint |
大整数 (ES6+) | 9007199254740991n |
string |
文本 | "Hello" |
symbol |
唯一标识符 (ES6+) | Symbol('id') |
2. 引用类型 (Reference Types)
| 类型 | 说明 | 示例 |
|---|---|---|
object |
对象基础类型 | { name: 'John' } |
array |
数组 | [1, 2, 3] |
function |
函数对象 | function() {} |
类型检测的 3 种方法
1. typeof 运算符
typeof "hello" // "string"typeof 42 // "number"typeof true // "boolean"typeof undefined // "undefined"typeof null // "object" (历史遗留问题)typeof Symbol() // "symbol"typeof 10n // "bigint"typeof {} // "object"typeof [] // "object"typeof function(){}// "function"
2. instanceof 检测原型链
[] instanceof Array // true{} instanceof Object // truenew Date() instanceof Date // true
3. Object.prototype.toString 终极方案
Object.prototype.toString.call("abc") // [object String]Object.prototype.toString.call(123) // [object Number]Object.prototype.toString.call(null) // [object Null]Object.prototype.toString.call(undefined) // [object Undefined]
类型转换
1. 显式类型转换
// 转数字Number("123") // 123parseInt("12.3") // 12parseFloat("12.3")// 12.3// 转字符串String(123) // "123"(123).toString() // "123"// 转布尔Boolean("") // false!!"hello" // true
2. 隐式类型转换(常见陷阱)
"5" + 2 // "52" (字符串拼接)"5" - 2 // 3 (自动转数字)null == undefined // true"0" == false // true
堆栈内存管理
1. 原始类型存储方式
let a = 10;let b = a; // 值拷贝b = 20;console.log(a); // 10 (原始值不受影响)
2. 引用类型存储方式
let obj1 = { count: 10 };let obj2 = obj1; // 地址引用拷贝obj2.count = 20;console.log(obj1.count); // 20 (共享同一内存)
常见问题及解决方案
1. 深拷贝实现
// 简单版(无法处理函数、循环引用)const deepCopy = obj => JSON.parse(JSON.stringify(obj));// 完整版(递归实现)function deepClone(source, map = new WeakMap()) {if (source instanceof Object) {if (map.has(source)) return map.get(source);let target = Array.isArray(source) ? [] : {};map.set(source, target);for (let key in source) {if (source.hasOwnProperty(key)) {target[key] = deepClone(source[key], map);}}return target;}return source;}
2. NaN 检测的正确姿势
// NaN 是唯一不等于自身的值const isNaN = value => value !== value;
3. 精确数值计算
// 使用整数计算0.1 * 10 + 0.2 * 10 === 0.3 * 10 // true// 使用 toFixed 格式化(0.1 + 0.2).toFixed(2) // "0.30"
ES6+ 新特性
1. BigInt 大整数处理
const max = 9007199254740991n; // 结尾加nconsole.log(max + 1n); // 9007199254740992n
2. Symbol 唯一标识符
const uid = Symbol('unique_id');const obj = {[uid]: '123456' // 防止属性名冲突};
总结
-
1.类型判断优先使用
Object.prototype.toString -
2.对象拷贝必须使用深拷贝
-
3.数值计算注意精度问题
-
4.类型比较使用严格相等
=== -
5.新特性合理使用 Symbol 和 BigInt
![]() |
Austin Liu 刘恒辉
Project Manager and Software Designer E-Mail:lzhdim@163.com Blog:https://lzhdim.cnblogs.com 欢迎收藏和转载此博客中的博文,但是请注明出处,给笔者一个与大家交流的空间。谢谢大家。 |




浙公网安备 33010602011771号