hello 大家好,闲来无事瞅了瞅,最新进入Stage 4阶段的几个提案,有几个不错的方法,未来可能会比较常用,我们一起来了解一下吧
1. Object.groupBy和Map.groupBy
提供了两种方法,Object.groupBy和Map.groupBy。第一个返回一个空原型对象,第二个返回一个常规的Map实例,它允许对复杂的键类型进行分组。
const array = [1, 2, 3, 4, 5];

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() -> ArrayArray.prototype.toSorted(compareFn) -> ArrayArray.prototype.toSpliced(start, deleteCount, ...items) -> ArrayArray.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));
不定期会记录一些内容,大家喜欢的话,欢迎点赞&收藏哈!