𝑻𝒆𝒏𝑪𝒍𝒂𝒘正在头脑风暴···
𝑻𝒆𝒏𝑲𝒊𝑺𝒆𝒀𝒂の𝑨𝒈𝒆𝒏𝒕助手
𝑻𝒆𝒏-𝒇𝒍𝒂𝒔𝒉

现代 JavaScript ES6+ 新特性总结

ES6 (ES2015) 是 JavaScript 历史上最重要的版本,之后不断更新。

变量声明

let 和 const

// let - 可重新赋值
let count = 0;
count = 1;

// const - 不可重新赋值
const name = '张三';
// name = '李四'; // Error

解构赋值

// 数组解构
const [a, b] = [1, 2];
const [first, ...rest] = [1, 2, 3];

// 对象解构
const { name, age } = { name: '张三', age: 25 };

// 函数参数解构
function greet({ name, age }) {
console.log(`${name}, ${age}岁`);
}

greet({ name: '李四', age: 30 });

箭头函数

// 传统函数
const add = (a, b) => {
return a + b;
};

// 箭头函数
const add = (a, b) => a + b;

// 无参数
const greet = () => console.log('Hello');

// 单个参数
const double = x => x * 2;

// 箭头函数没有 this
const obj = {
name: '张三',
greet: () => console.log(this.name)
};

字符串方法

模板字符串

const name = '张三';
const age = 25;

const greeting = `你好, ${name}! 今年 ${age} 岁`;

新增方法

const str = 'Hello World';

// includes
str.includes('World'); // true

// startsWith / endsWith
str.startsWith('Hello'); // true
str.endsWith('World'); // true

// repeat
str.repeat(3); // "Hello WorldHello WorldHello World"

// padStart / padEnd
str.padStart(10, '0'); // "000Hello World"
str.padEnd(20, '-'); // "Hello World---------"

数组方法

Flat 和 flatMap

const nested = [1, [2, [3, [4]]]];

nested.flat(); // [1, 2, [3, [4]]]
nested.flat(2); // [1, 2, 3, [4]]
nested.flat(Infinity); // [1, 2, 3, 4]

const arr = [1, 2, 3];
arr.flatMap(x => [x, x * 2]); // [1, 2, 2, 4, 3, 6]

indexOf 和 includes

const arr = [1, 2, 3];

arr.indexOf(2); // 1
arr.includes(2); // true

from 和 of

Array.from('abc');           // ['a', 'b', 'c']
Array.from({ length: 3 }); // [undefined, undefined, undefined]

Array.of(1, 2, 3); // [1, 2, 3]

entries, keys, values

const arr = ['a', 'b', 'c'];

// entries
Array.from(arr.entries()); // [[0, 'a'], [1, 'b'], [2, 'c']]

// keys
Array.from(arr.keys()); // [0, 1, 2]

// values
Array.from(arr.values()); // ['a', 'b', 'c']

对象扩展

简写

const name = '张三';
const age = 25;

// 之前
const obj1 = { name: name, age: age };

// 现在
const obj2 = { name, age };

展开运算符

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

const merged = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6]

const obj1 = { name: '张三', age: 25 };
const obj2 = { city: '北京' };

const mergedObj = { ...obj1, ...obj2 };

Object.assign 和展开

const target = { a: 1 };
const source = { b: 2, c: 3 };

const result = { ...target, ...source }; // { a: 1, b: 2, c: 3 }

属性名计算

const key = 'name';
const value = '张三';

const obj = {
[key]: value
};

Promise

基础用法

const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('成功');
}, 1000);
});

promise.then(value => {
console.log(value); // "成功"
}).catch(error => {
console.error(error);
});

Promise.all

const p1 = Promise.resolve(1);
const p2 = Promise.resolve(2);
const p3 = Promise.resolve(3);

Promise.all([p1, p2, p3]).then(values => {
console.log(values); // [1, 2, 3]
});

Promise.race

Promise.race([p1, p2, p3]).then(value => {
console.log(value);
});

Class

基础语法

class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}

greet() {
return `你好, ${this.name}`;
}
}

const person = new Person('张三', 25);
person.greet(); // "你好, 张三"

继承

class Employee extends Person {
constructor(name, age, salary) {
super(name, age);
this.salary = salary;
}

work() {
return `${this.name} 正在工作,月薪 ${this.salary}`;
}
}

静态方法

class MathUtils {
static add(a, b) {
return a + b;
}
}

MathUtils.add(1, 2); // 3

getters/setters

class Person {
constructor(name) {
this._name = name;
}

get name() {
return this._name;
}

set name(newName) {
this._name = newName;
}
}

模块化

导出

// 默认导出
export default function add(a, b) {
return a + b;
}

// 命名导出
export const name = '张三';
export function greet() {
console.log('Hello');
}

导入

// 默认导入
import add from './math';

// 命名导入
import { name, greet } from './utils';

迭代器

for…of

const arr = [1, 2, 3];

for (const num of arr) {
console.log(num);
}

Map 和 Set

// Map
const map = new Map();
map.set('name', '张三');
map.get('name'); // "张三"

// Set
const set = new Set();
set.add(1);
set.add(2);
set.has(1); // true

Symbol

const symbol = Symbol('description');

const obj = {
[symbol]: 'symbol value'
};

其他新特性

WeakMap 和 WeakSet

const key = {};
const map = new WeakMap();
map.set(key, 'value');

const weakSet = new WeakSet();
weakSet.add(key);

Number 新方法

Number.isFinite(1);         // true
Number.isNaN(NaN); // true
Number.isInteger(1.0); // true
Number.isInteger(1.2); // false

Number.EPSILON; // 2.220446049250313e-16
Number.MAX_SAFE_INTEGER; // 9007199254740991
Number.MIN_SAFE_INTEGER; // -9007199254740991

Math 新方法

Math.trunc(3.14);           // 3
Math.sign(-5); // -1
Math.cbrt(8); // 2

总结

ES6+ 带来了大量实用特性,包括:

  • let/const 声明
  • 箭头函数
  • 模板字符串
  • 解构赋值
  • Promise
  • Class
  • 模块化

持续关注 ES 最新特性,保持代码现代化!