ES6 (ECMAScript 2015) 新特性
About 3 min
ES6 (ECMAScript 2015) 新特性
ES6 是 JavaScript 语言的一次重大更新,引入了许多新特性,使 JavaScript 更现代化、更强大。以下是 ES6 的主要新特性:
1. 变量声明
- let 和 const
let
用于声明块级作用域的变量const
用于声明常量(不可重新赋值)- 替代了
var
的函数作用域和变量提升问题
let x = 10;
const PI = 3.14;
2. 箭头函数 (Arrow Functions)
- 更简洁的函数语法
- 自动绑定当前
this
值(不改变 this 指向) - 如果只有一个参数,可以省略括号
- 如果函数体只有一条语句,可以省略大括号和 return
const add = (a, b) => a + b;
const square = x => x * x;
3. 模板字符串 (Template Literals)
- 使用反引号
`
定义 - 支持多行字符串
- 支持字符串插值
${expression}
const name = 'Alice';
const greeting = `Hello, ${name}!
How are you today?`;
4. 解构赋值 (Destructuring Assignment)
- 从数组或对象中提取值并赋给变量
// 数组解构
const [a, b] = [1, 2];
// 对象解构
const { name, age } = { name: 'Bob', age: 30 };
// 函数参数解构
function greet({ name, age }) {
console.log(`Hello, ${name}. You are ${age}.`);
}
5. 默认参数 (Default Parameters)
- 函数参数可以设置默认值
function greet(name = 'Guest') {
console.log(`Hello, ${name}`);
}
6. 展开运算符 (Spread Operator) 和剩余参数 (Rest Parameters)
...
展开运算符可用于数组和对象- 剩余参数用于收集多个参数为数组
// 展开数组
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];
// 展开对象
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 };
// 剩余参数
function sum(...numbers) {
return numbers.reduce((acc, num) => acc + num, 0);
}
7. 对象字面量增强
- 属性简写
- 方法简写
- 计算属性名
const name = 'Alice';
const age = 25;
// 属性简写
const person = { name, age };
// 方法简写
const obj = {
sayHello() {
console.log('Hello');
}
};
// 计算属性名
const prop = 'lastName';
const person2 = {
firstName: 'John',
[prop]: 'Doe'
};
8. 类 (Classes)
- 更直观的面向对象编程语法
- 支持构造函数、方法、继承等
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello, ${this.name}`);
}
}
class Student extends Person {
constructor(name, grade) {
super(name);
this.grade = grade;
}
}
9. 模块化 (Modules)
import
和export
语法- 支持命名导出和默认导出
// math.js
export const PI = 3.14;
export function square(x) { return x * x; }
export default function add(a, b) { return a + b; }
// app.js
import add, { PI, square } from './math.js';
10. Promise
- 更好的异步编程解决方案
- 解决了回调地狱问题
const fetchData = () => {
return new Promise((resolve, reject) => {
// 异步操作
setTimeout(() => {
resolve('Data received');
}, 1000);
});
};
fetchData()
.then(data => console.log(data))
.catch(error => console.error(error));
11. 新的数据结构
- Set - 唯一值的集合
- Map - 键值对集合(键可以是任意类型)
- WeakSet 和 WeakMap - 弱引用版本
const set = new Set([1, 2, 3, 3]); // Set(3) {1, 2, 3}
const map = new Map();
map.set('name', 'Alice');
map.set({ id: 1 }, 'Object key');
12. 迭代器和 for...of 循环
- 可迭代协议和迭代器协议
for...of
循环用于遍历可迭代对象
const arr = [1, 2, 3];
for (const num of arr) {
console.log(num);
}
13. Symbol 类型
- 唯一且不可变的数据类型
- 常用于创建对象的唯一属性键
const sym = Symbol('description');
const obj = {
[sym]: 'value'
};
14. 新的字符串方法
includes()
,startsWith()
,endsWith()
repeat()
,padStart()
,padEnd()
'hello'.includes('ell'); // true
'hello'.repeat(3); // 'hellohellohello'
'5'.padStart(2, '0'); // '05'
15. 新的数组方法
Array.from()
- 从类数组对象创建数组Array.of()
- 创建数组find()
,findIndex()
- 查找元素fill()
- 填充数组includes()
- 检查是否包含某元素
Array.from('hello'); // ['h', 'e', 'l', 'l', 'o']
[1, 2, 3].find(x => x > 1); // 2