一、ES6 基础语法
1. let
和 const
声明变量
let
:块级作用域,可以重新赋值。const
:块级作用域,声明常量,不能重新赋值。
javascript
let name = 'Li Hua';
name = 'Li Ming'; // 可修改
const age = 21;
// age = 22; // 报错,const 不能重新赋值
2. 模板字符串
使用反引号 `````,支持 字符串插值 和 多行字符串。
javascript
const name = 'Li Hua';
const age = 21;
const message = `Hello, my name is ${name}. I'm ${age} years old.`;
console.log(message);
const multiLine = `这是一行
这又是另一行`;
console.log(multiLine);
3. 解构赋值
- 数组解构:
javascript
const [a, b, c] = [1, 2, 3];
console.log(a, b, c); // 1, 2, 3
- 对象解构:
javascript
const person = { name: 'Li Hua', age: 21 };
const { name, age } = person;
console.log(name, age); // 'Li Hua', 21
- 默认值:
javascript
const { city = 'Wuhan' } = {};
console.log(city); // 'Wuhan'
4. 箭头函数
箭头函数简化写法,并且不会绑定 this
。
javascript
const sum = (a, b) => a + b;
console.log(sum(3, 4)); // 7
const square = n => n * n;
console.log(square(5)); // 25
5. 扩展运算符 ...
- 数组展开:
javascript
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];
console.log(arr2); // [1, 2, 3, 4, 5]
- 对象合并:
javascript
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 };
console.log(obj2); // { a: 1, b: 2, c: 3 }
- 函数参数:
javascript
function sum(...numbers) {
return numbers.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
6. 默认参数
javascript
function greet(name = 'Guest') {
console.log(`Hello, ${name}!`);
}
greet(); // 'Hello, Guest!'
greet('Li Hua'); // 'Hello, Li Hua!'
7. for...of 遍历
javascript
const arr = [1, 2, 3];
for (const num of arr) {
console.log(num);
}
8. Promise 和异步操作
javascript
const fetchData = new Promise((resolve, reject) => {
setTimeout(() => resolve('数据加载成功'), 2000);
});
fetchData
.then(data => console.log(data))
.catch(err => console.log(err));
二、ES7+ 高级语法
1. ES7:includes
方法
javascript
const arr = [1, 2, 3];
console.log(arr.includes(2)); // true
console.log(arr.includes(5)); // false
2. ES8:Async/Await
javascript
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function loadData() {
console.log('开始加载...');
await delay(2000);
console.log('数据加载成功');
}
loadData();
3. ES9:对象的 Rest 和 Spread
- Rest 参数:
javascript
const { a, ...rest } = { a: 1, b: 2, c: 3 };
console.log(rest); // { b: 2, c: 3 }
- 对象展开:
javascript
const obj = { ...{ a: 1 }, b: 2 };
console.log(obj); // { a: 1, b: 2 }
4. ES10:Optional Catch Binding
javascript
try {
throw new Error('出错了');
} catch {
console.log('捕获异常');
}
5. ES11:可选链操作符 ?.
javascript
const user = { name: 'Li Hua', address: { city: 'Wuhan' } };
console.log(user.address?.city); // 'Wuhan'
console.log(user.contact?.phone); // undefined
6. ES12:逻辑赋值运算符
javascript
let a = null;
a ??= 'default';
console.log(a); // 'default'
let b = 5;
b &&= 10;
console.log(b); // 10