目录
ES6+特性概览
1. 变量声明:let和const
// var - 函数作用域,存在变量提升
var x = 10;
// let - 块级作用域,不可重复声明
let y = 20;
// const - 块级作用域,声明常量
const PI = 3.14159;
2. 箭头函数
// 传统函数
function add(a, b) {
return a + b;
}
// 箭头函数
const add = (a, b) => a + b;
// 单个参数可省略括号
const square = x => x x;
// 无参数
const sayHello = () => console.log("Hello!");
// 多行函数体
const multiply = (a, b) => {
const result = a b;
return result;
};
3. 模板字符串
const name = "Alice";
const age = 25;
// 传统字符串拼接
console.log("My name is " + name + " and I am " + age + " years old.");
// 模板字符串
console.log(`My name is ${name} and I am ${age} years old.`);
// 多行字符串
const message = `
Hello ${name},
Welcome to our website!
We're glad to have you here.
`;
4. 解构赋值
// 数组解构
const numbers = [1, 2, 3];
const [first, second, third] = numbers;
// 对象解构
const person = { name: "Bob", age: 30, city: "New York" };
const { name, age, city } = person;
// 重命名变量
const { name: personName, age: personAge } = person;
// 函数参数解构
function greet({ name, age }) {
return `Hello ${name}, you are ${age} years old!`;
}
5. 扩展运算符和剩余参数
// 扩展运算符(数组)
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6]
// 扩展运算符(对象)
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const merged = { ...obj1, ...obj2 }; // {a: 1, b: 2, c: 3, d: 4}
// 剩余参数
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
sum(1, 2, 3, 4); // 10
6. 默认参数
function greet(name = "Guest", greeting = "Hello") {
return `${greeting}, ${name}!`;
}
greet(); // "Hello, Guest!"
greet("Alice"); // "Hello, Alice!"
greet("Bob", "Hi"); // "Hi, Bob!"
7. 增强的对象字面量
const name = "Alice";
const age = 25;
// ES6之前
const person = {
name: name,
age: age,
sayHello: function() {
console.log("Hello!");
}
};
// ES6增强写法
const person = {
name, // 属性简写
age,
sayHello() { // 方法简写
console.log("Hello!");
},
// 计算属性名
[`${name}Info`]: "This is Alice's info"
};
8. Promise和异步编程
// 创建Promise
const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
const success = Math.random() > 0.5;
if (success) {
resolve("Data fetched successfully!");
} else {
reject("Error fetching data!");
}
}, 1000);
});
};
// 使用Promise
fetchData()
.then(data => console.log(data))
.catch(error => console.error(error));
// async/await (ES2017)
async function getData() {
try {
const data = await fetchData();
console.log(data);
} catch (error) {
console.error(error);
}
}
9. 模块化
// math.js - 导出模块
export const PI = 3.14159;
export function add(a, b) {
return a + b;
}
export default function multiply(a, b) {
return a b;
}
// app.js - 导入模块
import multiply, { PI, add } from './math.js';
console.log(PI); // 3.14159
console.log(add(2, 3)); // 5
console.log(multiply(2, 3)); // 6
10. 类(Class)
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
// 方法
greet() {
return `Hello, my name is ${this.name}`;
}
// 静态方法
static compareAges(person1, person2) {
return person1.age - person2.age;
}
}
// 继承
class Student extends Person {
constructor(name, age, grade) {
super(name, age); // 调用父类构造函数
this.grade = grade;
}
study() {
return `${this.name} is studying.`;
}
}
const alice = new Student("Alice", 20, "A");
console.log(alice.greet()); // "Hello, my name is Alice"
console.log(alice.study()); // "Alice is studying."
ES6+实际应用实例
1. 数组方法
const numbers = [1, 2, 3, 4, 5];
// map - 创建新数组
const doubled = numbers.map(n => n 2); // [2, 4, 6, 8, 10]
// filter - 过滤数组
const evens = numbers.filter(n => n % 2 === 0); // [2, 4]
// reduce - 累积值
const sum = numbers.reduce((total, n) => total + n, 0); // 15
// find - 查找元素
const firstEven = numbers.find(n => n % 2 === 0); // 2
// includes - 检查包含
const hasThree = numbers.includes(3); // true
2. 函数式编程示例
// 数据
const products = [
{ name: "Laptop", price: 1000, category: "electronics" },
{ name: "Phone", price: 500, category: "electronics" },
{ name: "Book", price: 20, category: "education" },
{ name: "Pen", price: 5, category: "education" }
];
// 链式操作
const expensiveElectronics = products
.filter(product => product.category === "electronics")
.filter(product => product.price > 300)
.map(product => ({
...product,
priceWithTax: product.price 1.1 // 添加10%税
}));
console.log(expensiveElectronics);
ES6+核心特性与实战应用
912

被折叠的 条评论
为什么被折叠?



