前端技巧第九期JavaScript数据类型

数据类型

一、原始类型 (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"     // "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   // true
new 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")     // 123
parseInt("12.3")  // 12
parseFloat("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;  // 结尾加n
console.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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值