数据类型
一、原始类型 (Primitive Types)
1:undefined
未赋值的默认类型 let a;
2:null
空值 let b = null;;
3:boolean
布尔值 true / false;
4:number
整数/浮点数/特殊数值 42 / 3.14 / NaN;
5:string
string “Hello”;
6:symbol
唯一标识符 (ES6+) Symbol(‘id’);
二、引用类型 (Reference Types)
1:object
对象基础类型 { name: ‘John’ };
2:array
数组 [1, 2, 3];
3:function
函数对象 function() {};
三、类型检测的 3 种方法
1.typeof
运算符
typeof "hello"
typeof 42
typeof true
typeof undefined
typeof null
typeof Symbol()
typeof 10n
typeof {}
typeof []
typeof function(){}
2. instanceof
检测原型链
[] instanceof Array
instanceof Object
new Date() instanceof Date
3. Object.prototype.toString
终极方案
Object.prototype.toString.call("abc")
Object.prototype.toString.call(123)
Object.prototype.toString.call(null)
Object.prototype.toString.call(undefined)
四、类型转换
1. 显式类型转换
Number("123")
parseInt("12.3")
parseFloat("12.3")
String(123)
(123).toString()
Boolean("")
!! "hello"
2. 隐式类型转换(常见陷阱)
"5" + 2
"5" - 2
null == undefined
"0" == false
五、堆栈内存管理
1. 原始类型存储方式
let a = 10;
let b = a;
b = 20;
console.log(a);
2. 引用类型存储方式
let obj1 = { count: 10 };
let obj2 = obj1;
obj2.count = 20;
console.log(obj1.count);
六、常见问题及解决方案
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
检测的正确姿势
const isNaN = value => value !== value;
3. 精确数值计算
0.1 * 10 + 0.2 * 10 === 0.3 * 10
(0.1 + 0.2).toFixed(2)
ES6+ 新特性
1. BigInt
大整数处理
const max = 9007199254740991n;
console.log(max + 1n);
2. Symbol
唯一标识符
const uid = Symbol('unique_id');
const obj = {
[uid]: '123456'
};
八、总结
1.类型判断优先使用 Object.prototype.toString
2.对象拷贝必须使用深拷贝
3.数值计算注意精度问题
4.类型比较使用严格相等 ===
5.新特性合理使用 Symbol 和 BigInt