即将发布的几种JS新方法(Stage 4阶段)

40 阅读1分钟

hello 大家好,闲来无事瞅了瞅,最新进入Stage 4阶段的几个提案,有几个不错的方法,未来可能会比较常用,我们一起来了解一下吧

image.png

1. Object.groupBy和Map.groupBy

提供了两种方法,Object.groupBy和Map.groupBy。第一个返回一个空原型对象,第二个返回一个常规的Map实例,它允许对复杂的键类型进行分组。

const array = [1, 2, 3, 4, 5];

![image.png](https://p6-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/f815410128f04d2d9ab2d3e5faf172a4~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAg5p6rOTEz:q75.awebp?rk3s=f64ab15b&x-expires=1770627957&x-signature=aIxuPzHnWq0MwubcJCjhMnv0Lpw%3D)
Object.groupBy(array, (num, index) => {
  return num % 2 === 0 ? 'even': 'odd';
});
// =>  { odd: [1, 3, 5], even: [2, 4] }

const odd  = { odd: true };
const even = { even: true };
Map.groupBy(array, (num, index) => {
  return num % 2 === 0 ? even: odd;
});
// =>  Map { {odd: true}: [1, 3, 5], {even: true}: [2, 4] }

2. 数组的新方法

下面4个方法都返回新的副本,不改变原数组本身

  • Array.prototype.toReversed() -> Array
  • Array.prototype.toSorted(compareFn) -> Array
  • Array.prototype.toSpliced(start, deleteCount, ...items) -> Array
  • Array.prototype.with(index, value) -> Array
const a = [1, 2, 3];
a.toReversed(); // => [3, 2, 1]
console.log(a); // => [1, 2, 3]

const b = [3, 1, 2];
b.toSorted(); // => [1, 2, 3]
console.log(b); // => [3, 1, 2]

const c = [1, 2, 3];
c.toSpliced(0,1); // [2, 3]
console.log(c); // => [1, 2, 3]

const d = [1, 1, 3];
d.with(1, 2); // => [1, 2, 3]
console.log(d); // => [1, 1, 3]

3. Promise.withResolvers

创建一个promise,然后返回promise、resolve、reject,可以将主动执行和回调结果分开调用

const { promise, resolve, reject } = Promise.withResolvers();
resolve('success');
promise.then((res)=>console.log(res));

不定期会记录一些内容,大家喜欢的话,欢迎点赞&收藏哈!