一、ES6 (ES2015) 重要新特性
1. 模板字符串 (Template Literals)
- 使用反引号(``)定义字符串
- 支持多行字符串和插值表达式
const name = 'Alice';
const greeting = `Hello, ${name}!`;
const multiLine = `
This is
a multi-line
string
`;
function tag(strings, ...values) {
console.log(strings);
console.log(values);
return strings[0] + values[0].toUpperCase() + strings[1];
}
const result = tag`Hello ${name}!`;
2. 箭头函数 (Arrow Functions)
const add = (a, b) => a + b;
const square = x => x * x;
const sayHi = () => console.log('Hi');
const makePerson = (name, age) => ({ name, age });
const counter = {
count: 0,
increment: function() {
setInterval(() => {
this.count++;
console.log(this.count);
}, 1000);
}
};
3. 函数参数增强
默认参数 (Default Parameters)
function greet(name = 'Guest', greeting = 'Hello') {
return `${greeting}, ${name}!`;
}
console.log(greet());
剩余参数 (Rest Parameters)
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3));
4. 解构赋值 (Destructuring Assignment)
对象解构
const person = { name: 'John', age: 30, city: 'New York' };
const { name, age } = person;
console.log(name, age);
const { name: personName } = person;
console.log(personName);
const { country = 'USA' } = person;
console.log(country);
数组解构
const numbers = [1, 2, 3];
const [first, second] = numbers;
console.log(first, second);
const [,, third] = numbers;
console.log(third);
const [head, ...tail] = numbers;
console.log(tail);
5. 对象字面量增强
属性简写
const name = 'Alice';
const age = 25;
const person = { name, age };
方法简写
const obj = {
sayHello: function() {},
sayHi() {},
sayBye: () => {}
};
计算属性名
const propKey = 'name';
const obj = {
[propKey]: 'John',
[`get${propKey}`]() {
return this[propKey];
}
};
console.log(obj.getName());
二、ES2016 (ES7) 新特性
1. 数组 includes() 方法
const arr = [1, 2, 3];
console.log(arr.includes(2));
console.log(arr.includes(4));
console.log([NaN].includes(NaN));
console.log([NaN].indexOf(NaN) !== -1);
2. 指数运算符 (**)
console.log(2 ** 3);
console.log(Math.pow(2, 3));
console.log((-2) ** 3);
console.log(Math.pow(-2, 3));
三、ES2017 (ES8) 新特性
1. async/await
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:', error);
}
}
2. Object.values() / Object.entries()
const obj = { a: 1, b: 2, c: 3 };
console.log(Object.values(obj));
console.log(Object.entries(obj));
for (const [key, value] of Object.entries(obj)) {
console.log(`${key}: ${value}`);
}
3. 字符串填充方法
console.log('5'.padStart(2, '0'));
console.log('12'.padStart(2, '0'));
console.log('abc'.padEnd(5, '*'));
4. 函数参数列表尾逗号
function foo(
param1,
param2,
) {
}
四、ES2018 (ES9) 新特性
1. 对象扩展运算符
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 };
const obj3 = { ...obj1, a: 3 };
const obj4 = { ...obj1 };
console.log(obj4 === obj1);
2. Promise.finally()
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error))
.finally(() => console.log('Request completed'));
3. 正则表达式增强
命名捕获组
const re = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const match = re.exec('2023-05-15');
console.log(match.groups.year);
dotAll 模式 (s 标志)
const re = /foo.bar/s;
console.log(re.test('foo\nbar'));
后行断言
console.log(/(?<=\$)\d+/.exec('$100')[0]);
console.log(/(?<!\$)\d+/.exec('€100')[0]);
五、ES2019 (ES10) 新特性
1. Array.flat() / Array.flatMap()
const arr = [1, [2, [3]]];
console.log(arr.flat());
console.log(arr.flat(2));
const sentences = ["Hello world", "Goodbye universe"];
const words = sentences.flatMap(sentence => sentence.split(' '));
console.log(words);
2. Object.fromEntries()
const entries = [['name', 'John'], ['age', 30]];
const obj = Object.fromEntries(entries);
console.log(obj);
const newObj = Object.fromEntries(
Object.entries(obj).map(([key, value]) => [key, String(value)])
);
3. String.trimStart() / String.trimEnd()
const str = ' hello ';
console.log(str.trimStart());
console.log(str.trimEnd());
4. 可选的 catch 绑定
try {
} catch {
console.log('An error occurred');
}
六、ES2020 (ES11) 新特性
1. 可选链操作符 (?.)
const user = { profile: { name: 'John' } };
const name = user && user.profile && user.profile.name;
const name = user?.profile?.name;
user.sayHi?.();
const firstItem = arr?.[0];
2. 空值合并运算符 (??)
const value = null ?? 'default';
const value2 = 0 ?? 'default';
console.log(0 || 'default');
console.log('' || 'default');
console.log(false || 'default');
3. 动态导入 (Dynamic Import)
button.addEventListener('click', async () => {
const module = await import('./module.js');
module.doSomething();
});
4. BigInt
const bigNum = 9007199254740991n;
const anotherBigNum = BigInt("9007199254740991");
console.log(bigNum + anotherBigNum);
console.log(bigNum + 1);
七、ES2021 (ES12) 新特性
1. 逻辑赋值运算符
let a = false;
a ||= true;
let b = true;
b &&= false;
let c = null;
c ??= 'default';
2. String.replaceAll()
const str = 'hello world';
console.log(str.replaceAll('l', 'x'));
console.log(str.replace(/l/g, 'x'));
3. Promise.any()
const promises = [
Promise.reject('Error 1'),
Promise.resolve('Success 1'),
Promise.reject('Error 2')
];
Promise.any(promises)
.then(result => console.log(result))
.catch(errors => console.log(errors));
4. 数字分隔符
const billion = 1_000_000_000;
console.log(billion === 1000000000);
八、ES2022 (ES13) 新特性
1. 类字段声明
class Counter {
count = 0;
increment = () => {
this.count++;
};
static version = '1.0';
}
2. 私有字段和方法
class Person {
#name;
constructor(name) {
this.#name = name;
}
#privateMethod() {
return `Hello, ${this.#name}`;
}
greet() {
console.log(this.#privateMethod());
}
}
const person = new Person('John');
person.greet();
3. 静态初始化块
class Translator {
static translations = {
yes: 'ja',
no: 'nein'
};
static englishWords = [];
static germanWords = [];
static {
for (const [english, german] of Object.entries(this.translations)) {
this.englishWords.push(english);
this.germanWords.push(german);
}
}
}
4. 顶层 await
const data = await fetchData();
console.log(data);
(async () => {
const data = await fetchData();
console.log(data);
})();
九、ES2023 (ES14) 新特性
1. Array.findLast() / Array.findLastIndex()
const numbers = [1, 2, 3, 4, 3, 2, 1];
console.log(numbers.findLast(n => n > 2));
console.log(numbers.findLastIndex(n => n > 2));
2. Hashbang 语法标准化
#!/usr/bin/env node
console.log('Hello from CLI tool');
3. WeakMap 支持 Symbol 键
const weakMap = new WeakMap();
const key = Symbol('privateData');
const obj = {};
weakMap.set(key, 'secret');
weakMap.set(obj, 'other secret');
console.log(weakMap.get(key));
console.log(weakMap.get(obj));
十、总结与应用建议
1. 版本特性快速参考
| 版本 | 重要特性 |
|---|
| ES6 | 类、模块、箭头函数、模板字符串、解构、Promise、let/const |
| ES2016 | includes()、指数运算符 |
| ES2017 | async/await、Object.values/entries、字符串填充 |
| ES2018 | 对象扩展运算符、Promise.finally、正则增强 |
| ES2019 | Array.flat/flatMap、Object.fromEntries、trimStart/End |
| ES2020 | 可选链、空值合并、动态导入、BigInt |
| ES2021 | 逻辑赋值、replaceAll、Promise.any、数字分隔符 |
| ES2022 | 类字段、私有方法、静态块、顶层await |
| ES2023 | Array.findLast、Hashbang、WeakMap Symbol键 |
2. 现代JavaScript开发建议
- 优先使用新语法:如箭头函数、模板字符串、解构赋值等
- 渐进式采用:根据项目环境逐步引入新特性
- 关注兼容性:使用Babel等工具确保代码兼容性
- 代码可读性:合理使用新特性提升代码可读性而非炫技
- 团队一致性:制定团队编码规范统一新特性的使用方式
3. 学习资源推荐
- 官方文档:ECMAScript规范
- 兼容性查询:Can I use
- 实践教程:现代JavaScript教程
- 新特性演示:ES6+示例