简介
《Types & Grammar》深入讲解 JavaScript 的类型系统和语法细节,帮助你避免类型相关的坑。
JavaScript 类型
基本类型 (Primitive Types)
JavaScript 有 7 种基本类型:
// 1. Undefined
typeof undefined; // "undefined"
// 2. String
typeof "hello"; // "string"
// 3. Number
typeof 42; // "number"
typeof 3.14; // "number"
// 4. Boolean
typeof true; // "boolean"
// 5. Symbol (ES6+)
typeof Symbol(); // "symbol"
// 6. BigInt (ES2020+)
typeof 123n; // "bigint"
// 7. Null (历史 bug)
typeof null; // "object" - 错误!
值 vs 引用
基本类型 - 按值传递
let a = 2;
let b = a; // 复制值
b = 3;
console.log(a); // 2 - 独立副本
引用类型 - 按引用传递
let a = { x: 1 };
let b = a; // 复制引用(指向同一对象)
b.x = 2;
console.log(a.x); // 2 - 同一个对象
函数参数
function modify(value) {
value = 42;
}
let num = 1;
modify(num);
console.log(num); // 1 - 基本类型不受影响
function modifyObj(obj) {
obj.x = 42;
}
let o = { x: 1 };
modifyObj(o);
console.log(o.x); // 42 - 引用类型被修改
类型转换
显式转换
// 字符串转数字
Number("42"); // 42
parseInt("42"); // 42
parseFloat("3.14"); // 3.14
+"42"; // 42 (一元加号)
// 数字转字符串
String(42); // "42"
(42).toString(); // "42"
42 + ""; // "42"
// 转布尔值
Boolean(1); // true
!!1; // true
Boolean(0); // false
!!0; // false
隐式转换
// 字符串和数字
"42" + 1; // "421" - 数字转字符串
"42" - 1; // 41 - 字符串转数字
// 布尔值转换
if ("hello") { // true - 真值
console.log("yes");
}
!!"hello"; // true
// 宽松相等 ==
"42" == 42; // true - 类型转换
null == undefined; // true
0 == false; // true
// 严格相等 ===
"42" === 42; // false - 不转换
装箱 (Boxing)
基本类型可以自动”装箱”为引用类型:
"hello".length; // 5 - String 对象
(42).toFixed(2); // "42.00" - Number 对象
true.toString(); // "true" - Boolean 对象
NaN
typeof NaN; // "number"
// NaN 是唯一不等于自身的值
NaN === NaN; // false
Number.isNaN(NaN); // true
Number.isNaN("hello"); // false
特殊数值
// Infinity
Infinity;
-Infinity;
1 / 0; // Infinity
// 0 和 -0
0 === -0; // true
1 / 0 === 1 / -0; // false
// 精确浮点数
0.1 + 0.2; // 0.30000000000000004
强制转型 (Coercion)
ToPrimitive
// 对象转基本类型
[1, 2] + [3, 4]; // "1,23,4" - 先转字符串再拼接
// valueOf / toString
const obj = {
valueOf() { return 42; },
toString() { return "hello"; }
};
String(obj); // "hello" - toString 优先
Number(obj); // 42 - valueOf 优先
obj + ""; // "42"
小结
- ✅ 掌握 7 种基本类型
- ✅ 理解值传递和引用传递的区别
- ✅ 熟练使用显式和隐式类型转换
- ✅ 了解 NaN 的特殊性质
- ✅ 始终优先使用
===严格相等
相关阅读: