JavaScript 变量类型深度解析
原始类型(Primitive Types)
JavaScript 中原始类型数据直接存储在栈内存中,具有不可变性。
7种原始类型
-
Undefined:声明未赋值的变量
let a; // typeof a => 'undefined' -
Null:空值引用
let b = null; // typeof b => 'object'(历史遗留问题) -
Boolean:逻辑值
let c = true; // typeof c => 'boolean' -
Number:双精度浮点数
let d = 42; // typeof d => 'number' -
String:UTF-16 字符串
let e = "hello"; // typeof e => 'string' -
Symbol(ES6):唯一值标识符
let f = Symbol('id'); // typeof f => 'symbol' -
BigInt(ES2020):大整数
let g = 9007199254740991n; // typeof g => 'bigint'
引用类型(Reference Types)
存储在堆内存中,变量保存的是内存地址引用。
常见引用类型
- Object:
{}
- Array:
[]
- Function:
function() {}
- Date
- RegExp
- 自定义对象
特性示例
let obj1 = { name: 'John' };let obj2 = obj1; // 复制引用地址obj2.name = 'Alice';console.log(obj1.name); // 'Alice'(联动修改)
console.log({} === {}); // false(比较的是内存地址)
类型转换
隐式转换
// 转换为 Booleanif (0) { /* 不会执行 */ } // 0 → false
// 转换为 Stringconsole.log(1 + '2'); // '12'
// 转换为 Numberconsole.log('3' * 2); // 6
显式转换
String(123); // '123'Number('42'); // 42Boolean('hello'); // trueparseInt('10px'); // 10
转换规则表
原始值 | 转 Boolean | 转 Number | 转 String |
---|---|---|---|
"" | false | 0 | "" |
"0” | true | 0 | ”0" |
"42” | true | 42 | ”42” |
null | false | 0 | ”null” |
undefined | false | NaN | ”undefined” |
true | NaN | ”[object Object]“ |
类型判断
1. typeof 操作符
typeof undefined; // 'undefined'typeof 42; // 'number'typeof Symbol(); // 'symbol'typeof function(){}// 'function'typeof null; // 'object'(需要注意)
2. instanceof
检测原型链:
[] instanceof Array; // truenew Date() instanceof Date; // true
3. Object.prototype.toString
最准确的类型判断:
Object.prototype.toString.call([]);// "[object Array]"
Object.prototype.toString.call(null);// "[object Null]"
类型判断最佳实践
function getType(target) { return Object.prototype.toString.call(target) .slice(8, -1) .toLowerCase();}
getType([]); // 'array'getType(null); // 'null'
注意事项
- 浮点数精度:
0.1 + 0.2 !== 0.3
- 类型转换陷阱:
==
会进行隐式转换,建议使用===
- 深拷贝问题:引用类型需要递归拷贝
- 包装对象:临时对象机制
let s = 'hello';s.name = 'str'; // 临时创建包装对象,随后销毁console.log(s.name); // undefined