ES6 新特性概览
2025/12/1大约 3 分钟
ES6 新特性概览
1. let 和 const
let
- let 声明的变量只在块级作用域内有效,而 var 声明的变量在全局范围内有效。
{
let a = 10;
var b = 1;
}
console.log(a); // ReferenceError: a is not defined
console.log(b); // 1- let 声明的变量不能在声明前使用,而 var 声明的变量可以在声明前使用。
console.log(a); // ReferenceError: a is not defined
let a = 10;
console.log(b); // undefined
var b = 1;const
- const 声明的变量必须在声明时初始化,且不能重新赋值。
const a = 10;
a = 20; // TypeError: Assignment to constant variable.- const 声明的变量只在块级作用域内有效。
{
const a = 10;
}
console.log(a); // ReferenceError: a is not defined2. 箭头函数
- 箭头函数简化了函数的写法,并且不绑定自己的 this 值。
// 传统写法
var add = function(a, b) {
return a + b;
};
// 箭头函数写法
const add = (a, b) => a + b;3. 模板字符串
- 模板字符串使用反引号(`)标识,可以嵌入变量和表达式。
const name = 'John';
const age = 30;
const message = `My name is ${name} and I am ${age} years old.`;
console.log(message); // My name is John and I am 30 years old.4. 解构赋值
- 解构赋值允许从数组或对象中提取数据,并赋值给变量。
// 数组解构
const [a, b, c] = [1, 2, 3];
console.log(a, b, c); // 1 2 3
// 对象解构
const { name, age } = { name: 'John', age: 30 };
console.log(name, age); // John 305. 默认参数
- 默认参数允许在函数定义时为参数指定默认值。
function greet(name = 'John') {
console.log(`Hello, ${name}!`);
}
greet(); // Hello, John!
greet('Alice'); // Hello, Alice!6. 展开运算符
- 展开运算符(...)允许将一个数组或对象展开为单独的元素或属性。
// 数组展开
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];
console.log(arr2); // [1, 2, 3, 4, 5]
// 对象展开
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 };
console.log(obj2); // { a: 1, b: 2, c: 3 }7. Promise
- Promise 用于处理异步操作,提供了更清晰的代码结构。
const myPromise = new Promise((resolve, reject) => {
const success = true;
if (success) {
resolve('Operation successful!');
} else {
reject('Operation failed.');
}
});
myPromise
.then(message => console.log(message)) // Operation successful!
.catch(error => console.error(error));8. async/await
- async/await 是基于 Promise 的语法糖,用于处理异步操作,使代码更简洁易读。
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
fetchData();9. 类
- 类是 ES6 中引入的一种新的语法,用于创建对象和定义对象的行为。
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
const john = new Person('John', 30);
john.greet(); // Hello, my name is John and I am 30 years old.10. 模块
- 模块是 ES6 中引入的一种新的语法,用于组织代码和共享代码。
// module.js
export const name = 'John';
export const age = 30;
// main.js
import { name, age } from './module.js';
console.log(name, age); // John 3011. Set 和 Map
- Set 是一种新的数据结构,用于存储唯一值。
const set = new Set([1, 2, 3, 4, 4, 5]);
console.log(set); // Set { 1, 2, 3, 4, 5 }- Map 是一种新的数据结构,用于存储键值对。
const map = new Map();
map.set('name', 'John');
map.set('age', 30);
console.log(map); // Map { 'name' => 'John', 'age' => 30 }12. for...of 循环
- for...of 循环用于遍历可迭代对象(如数组、字符串、Map、Set 等)。
const arr = [10, 20, 30];
for (const value of arr) {
console.log(value);
}
// 10
// 20
// 30