Skip to content

Async iterators 迭代器

Object spread operators 对象展开

js
const obj = { name: "tom" };
const newObj = { ...obj };

Promise finally 方法

flat flatMap 数组降维

flat() 方法会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返。 flatMap() 方法首先使用映射函数映射每个元素 ,然后将结果压缩成一个新数组。

  • flatMap 是先进行 map 操作,再做 flat 的操作;
  • flatMap 中的 flat 相当于深度为 1。
js
// 1. flat的使用
const nums = [
  10,
  20,
  [2, 9],
  [
    [30, 40],
    [10, 45],
  ],
  78,
  [55, 88],
];
const newNums = nums.flat();
// 打印 [10, 20, 2, 9, [30, 40], [10, 45], 78, 55, 88]
console.log(newNums);
const newNums2 = nums.flat(2);
// 打印 [10, 20, 2, 9, 30, 40, 10, 45, 78, 55, 88]
console.log(newNums2);

// 2. flatMap的使用
const messages = ["Hello World", "hello lyh", "my name is coderwhy"];
const words = messages.flatMap((item) => {
  // 如果return数组,则会把return的数组降维
  return item.split(" ");
});
// ["Hello", "World", "hello", "lyh", "my", "name", "is", "coderwhy"]
console.log(words);

Object fromEntries

在前面,我们可以通过 Object.entries 将一个对象转换成 entries,那么如果我们有一个 entries 了,如何将其转换成对象呢? ES10 提供了 Object.formEntries 来完成转换:

js
const obj = {
  name: "tom"
  age: 18,
  weight: 50,
}
const entries = Object.entries(obj)
// 打印 [['name', 'tom'], ['age', 18 ], ['weight', 50 ]]
console.log(entries)
const newObj = Object.fromEntries(entries)
// 打印{ name: "tom", age: 18, weight: 50 }
console.log(newObj)

trimStart trimEnd

trim 方法差不多,trimStarttrimEnd 是用来分别去除前面或者后面的空白字符。

Symbol description

js
const s = Symbol("aaa");
// 打印 'aaa'
console.log(s.description);

Optional catch binding