一些便捷的ES语法使用记录
Object.values()
const exampleObj = {a: 1, b: 2, c: 3, d:4};
console.log(Object.value(exampleObj)); // [1, 2, 3, 4];
Object.keys()
const values = Object.keys(exampleObj).map(key => exampleObj[key]);
Object.entries()
const exampleObj = {a: 1, b: 2, c: 3, d:4};
console.log(Object.entries(exampleObj)); // [["a", 1], ["b", 2], ["c", 3], ["d", 4]];
for (const [key, value] of Object.entries(exampleObj)) {
console.log(`key: ${key}, value: ${value}`);
}
字符串 padStart()
String.padStart(fillingLength, FillingContent);
'100'.padStart(5, '987'); // 98100
字符串 padEnd()
'100'.padStart(5, '987'); // 10098
ES9 异步迭代器
允许 await 与 for 循环一起使用,逐步执行异步操作
async function process(array) {
for await (const i of array) {
doSomething(i);
}
}
Math.max()
const values = [19, 90, -2, 6, 25];
console.log( Math.max(...values) ); // 90
正则表达式组
RegExp 可以返回匹配的数据包
const regExpDate = /([0-9]{4})-([0-9]{2})-([0-9]{2})/;
const match = regExpDate.exec('2020-06-25');
const year = match[1]; // 2020
const month = match[2]; // 06
const day = match[3]; // 25
Array.prototype.flat()
展平阵列
const arr1 = [1, 2, [3, 4]];
arr1.flat(); // [1, 2, 3, 4]
const arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat(); // [1, 2, 3, 4, [5, 6]]
arr2.flat(2); // [1, 2, 3, 4, 5, 6]
Array.prototype.flatMap()
展平一个维度
let arr = ["早安", "", "今天天氣不錯"]
arr.map(s => s.split(""))
// [["早", "安"], [""], ["今", "天", "天", "氣", "不", "錯"]]
arr.flatMap(s => s.split(''));
// ["早", "安", "", "今", "天", "天", "氣", "不", "錯"]
String.prototype.trimStart()
开头删除空格,别名trimLeft()
const greeting = ‘ Hello world! ‘;
console.log(greeting.trimStart());
// expected output: “Hello world! “;
String.prototype.trimEnd()
末尾删除空格,别名trimRight()
const greeting = ' Hello world! ';
console.log(greeting.trimEnd());
// expected output: " Hello world!";
Object.fromEntries()
将键值对列表转换为对象
const entries = new Map([
['foo', 'bar'],
['baz', 42]
]);
const obj = Object.fromEntries(entries);
console.log(obj);
// expected output: Object { foo: "bar", baz: 42 }
Promise.allSettled()
返回一个在所有给定的 Promise 都已实现或拒绝后实现的 Promise,并带有一组对象,每个对象都描述了每个 Promise 的结果
const promise1 = Promise.resolve(3);
const promise2 = new Promise((resolve, reject) => setTimeout(reject, 100, 'foo'));
const promises = [promise1, promise2];
Promise.allSettled(promises).
then((results) => results.forEach((result) => console.log(result.status)));
// expected output:
// "fulfilled"
// "rejected"
可选链接?
//如果存在,获取name的值,如果不存在,赋值undefined
const username = user?.name || 'guest';
Nullish 合并运算符 ??
在JavaScript中,遇到0、null、undefuded时会自动转为false,但有时0其实是一个正常的值,只能容错undefined和null
const username = user.level ?? 'no level';
// output 0. if level is not available, it becomes 'no level'.
Dynamic-import
在需要的时候加载相关的逻辑
el.onclick = () => {
import(`/js/current-logic.js`)
.then((module) => {
module.doSomthing();
})
.catch((err) => {
handleError(err);
})
}
||= , &&= , ??=
ES2021 会提出 ||= , &&= , ??= ,概念类似于 += :
let b = 2
b += 1
// equal to b = b + 1
let a = null
a ||= 'some random text' // a become to'some random text'
// equal a = a || 'some random text'
let c = 'some random texts'
c &&= null // c become to null
// equal to c = c && null
let d = null
d ??= false // d become to false
// equal to d = d ?? false