掌握变量声明和数据类型的基础知识
| 关键字 | 作用域 | 可重新赋值 | 可重复声明 | 推荐使用 |
|---|---|---|---|---|
| let | 块级作用域 | 是 | 否 | 是 |
| const | 块级作用域 | 否 | 否 | 是 (优先) |
| var | 函数作用域 | 是 | 是 | 否 |
// 使用 const 声明常量(推荐)
const PI = 3.14159;
// 使用 let 声明变量
let count = 0;
count = 1; // 可以重新赋值
// 坚决不用 var
var oldVariable = 'old'; // 避免使用// 字符串
const name = 'John';
// 数字
const age = 30;
const pi = 3.14;
// 布尔值
const isActive = true;
// 空值
const emptyValue = null;
// 未定义
let undefinedValue;
// Symbol
const uniqueId = Symbol('id');
// BigInt
const bigNumber = 9007199254740991n;// 精确的数学计算
const result1 = 0.1 + 0.2; // 传统方式:0.30000000000000004
// 使用新的精确数学方法
const result2 = Math.sum(0.1, 0.2); // 2026 新特性:0.3
// 其他新方法
const average = Math.mean(1, 2, 3); // 2
const median = Math.median(1, 3, 2); // 2// BigInt 运算
const big1 = 9007199254740991n;
const big2 = 9007199254740991n;
const sum = big1 + big2; // 18014398509481982n
// 与普通数字转换
const num = 123;
const bigNum = BigInt(num);
const backToNum = Number(bigNum);// 转换为数字
const str = '123';
const num = Number(str); // 123
const num2 = +str; // 123(简写方式)
// 转换为字符串
const num3 = 123;
const str2 = String(num3); // '123'
const str3 = num3 + ''; // '123'(简写方式)
// 转换为布尔值
const value = 'hello';
const bool = Boolean(value); // true
const bool2 = !!value; // true(简写方式)// typeof 操作符
typeof 'hello'; // 'string'
typeof 123; // 'number'
typeof true; // 'boolean'
typeof null; // 'object'(历史遗留问题)
typeof undefined; // 'undefined'
typeof Symbol(); // 'symbol'
typeof 123n; // 'bigint'
// 检测数组
Array.isArray([1, 2, 3]); // true
// 检测 null
const value = null;
value === null; // true
// 检测 undefined
let undefinedValue;
undefinedValue === undefined; // true// 传统的安全检测
const user = { name: 'John' };
if (user && user.address && user.address.street) {
console.log(user.address.street);
}
// 使用可选链(现代方式)
const street = user?.address?.street;
console.log(street); // undefined(不会报错)不可变性意味着一旦创建了数据,就不能直接修改它。而是创建一个新的数据副本。
// 可变的方式(不推荐)
let arr = [1, 2, 3];
arr.push(4); // 直接修改原数组
// 不可变的方式(推荐)
const arr2 = [1, 2, 3];
const newArr = [...arr2, 4]; // 创建新数组
// 对象的不可变操作
const user = { name: 'John', age: 30 };
const newUser = { ...user, age: 31 }; // 创建新对象