你不需要使用 Array.reduce()
由 Mux 赞助的 DEV 全球展示挑战赛:展示你的项目!
我读了另一篇 dev.to 帖子《揭秘》Array.reduce(),但我对使用它仍然没有信心Array.reduce()。
Array.reduce()也许我的方法也不对,但每次我这样做,最终都会不喜欢它,然后转而使用简单的for..of循环。
接下来是那篇文章中的三个示例,经过转换后for..of,在我看来更容易阅读和更清晰。
以求和为例:
const array = [1, 2, 3, 4];
const sum = array.reduce((accumulator, currentItem) => {
return accumulator + currentItem;
}, 0);
// sum = 10
它可以写成
const array = [1, 2, 3, 4]
let sum = 0
for (const n of array) sum += n
// sum = 10
这样就简单多了!
下一个例子,
const trips = [{type: 'car', dist: 42}, {type: 'foot', dist: 3}, {type:'flight', dist: 212}, {type: 'car', dist: 90}, {type: 'foot', dist: 7}]
const distanceByType = trip.reduce((out, curr) => {
const { type, dist } = curr;
if (out[type]) {
out[type] += dist;
} else {
out[type] = dist;
}
return out;
}, {});
// distanceByType = {car: 132, foot: 10, flight: 212};
可以改写为
const trips = [{type: 'car', dist: 42}, {type: 'foot', dist: 3}, {type:'flight', dist: 212}, {type: 'car', dist: 90}, {type: 'foot', dist: 7}]
const distanceByType = {}
for (const trip of trips) {
const { type, dist } = trip
if (distanceByType[type]) {
distanceByType[type] += dist
} else {
distanceByType[type] = dist
}
}
// distanceByType = {car: 132, foot: 10, flight: 212}
简单的!
最后,举个评论中关于管道函数的例子:
const pipeOnce = (fn1, fn2) => (args) => (fn2(fn1(args)));
const pipe = (...ops) => ops.reduce(pipeOnce);
const addTwo = a => a + 2;
const mulTwo = a => a * 2;
const addTwoMulTwo = pipe(addTwo, mulTwo);
console.log(addTwoMulTwo(1)); // (1 + 2) * 2 => 6
console.log(addTwoMulTwo(2)); // (2 + 2) * 2 => 8
console.log(addTwoMulTwo(3)); // (3 + 2) * 2 => 10
是 reduce 的一个更好例子,但它也可以写成
const addTwo = a => a + 2;
const mulTwo = a => a * 2;
const addTwoMulTwo = n => mulTwo(addTwo(n))
console.log(addTwoMulTwo(1)); // (1 + 2) * 2 => 6
console.log(addTwoMulTwo(2)); // (2 + 2) * 2 => 8
console.log(addTwoMulTwo(3)); // (3 + 2) * 2 => 10
如果我们想通过管道传递任意数量的函数,也可以这样做for..of:
const pipe = (...fns) => arg => {
for (const fn of fns) arg = fn(arg)
return arg
}
const addTwoMulTwo = pipe(addTwo, mulTwo)
这篇虽然篇幅较长,但更容易理解。
在哪些使用场景下,它比其他替代方案Array.reduce() 更胜一筹for..of?
如果您知道,请分享!
文章来源:https://dev.to/trusktr/you-dont-need-arrayreduce-557f