1. let 和 const
let x = 10;
const PI = 3.14;
{
let x = 20;
const y = 30;
}
2. 箭头函数
function add(a, b) {
return a + b;
}
const add = (a, b) => a + b;
const obj = {
name: 'test',
sayTraditional: function() {
setTimeout(function() {
console.log(this.name);
}, 100);
},
sayArrow: function() {
setTimeout(() => {
console.log(this.name);
}, 100);
}
};
3. 解构赋值
const [a, b] = [1, 2];
const { name, age } = { name: 'John', age: 30 };
const { title = 'Default' } = {};
const { address: { city } } = person;
4. 模板字符串
const name = 'John';
const greeting = `Hello ${name}!
This is a multiline
string`;
5. 扩展运算符
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];
const obj1 = { foo: 'bar', x: 42 };
const obj2 = { ...obj1, y: 13 };
const numbers = [1, 2, 3];
console.log(Math.max(...numbers));
6. Promise
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('success');
}, 1000);
});
promise
.then(result => console.log(result))
.catch(error => console.error(error));
async function fetchData() {
try {
const result = await promise;
console.log(result);
} catch (error) {
console.error(error);
}
}
7. 类(Class)
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound`;
}
}
class Dog extends Animal {
speak() {
return `${this.name} barks`;
}
}
8. 模块化
export const PI = 3.14;
export function square(x) {
return x * x;
}
export default class User {
}
import { PI, square } from './math.js';
import User from './user.js';
9. Map 和 Set
const map = new Map();
map.set('key', 'value');
map.get('key');
const set = new Set([1, 2, 3, 3]);
10. 默认参数
function greet(name = 'Guest') {
return `Hello ${name}!`;
}
11. Object 新方法
const target = { a: 1 };
const source = { b: 2 };
const result = Object.assign(target, source);
const obj = { a: 1, b: 2 };
Object.keys(obj);
Object.values(obj);
Object.entries(obj);
12. Array 新方法
[1, 2, 3].includes(2);
[1, 2, 3].find(x => x > 1);
[1, 2, 3].findIndex(x => x > 1);
Array.from('hello');
13. 可选链操作符(ES2020)
const user = {
address: {
street: 'Main St'
}
};
const street = user && user.address && user.address.street;
const street = user?.address?.street;
14. 空值合并操作符(ES2020)
const foo = null ?? 'default';
const bar = 0 ?? 'default';
15. BigInt(ES2020)
const bigInt = 9007199254740991n;
const result = bigInt + 1n;