【发布时间】:2020-05-10 10:03:24
【问题描述】:
将Array.prototype.reduce 与Array.prototype.filter 链接时,在过滤当前值而不是累加器值时有什么区别(概念上和底层)?
// function union creates a union of all values that appear among arrays
// example A
const union = (...arrays) => {
return arrays.reduce((acc, curr) => {
const newElements = acc.filter(el => !curr.includes(el));
return curr.concat(newElements);
});
};
console.log(union([1, 10, 15, 20], [5, 88, 1, 7], [1, 10, 15, 5]));
// output (7) [1, 10, 15, 5, 88, 7, 20]
// example B
const union = (...arrays) => {
return arrays.reduce((acc, curr) => {
const newElements = curr.filter(el => !acc.includes(el));
return acc.concat(newElements);
});
};
console.log(union([1, 10, 15, 20], [5, 88, 1, 7], [1, 10, 15, 5]));
//output (7) [1, 10, 15, 20, 5, 88, 7]
输出的差异表明计算数组的顺序是“相反的”。据我所知,在使用 arr.filter 时,这些值是从头到尾评估的,而 curr.filter 则相反。除此之外,如果您通过累加器或当前值过滤,它们是否还有其他后果?这会在不同的上下文中引发错误吗?
【问题讨论】:
标签: javascript arrays function functional-programming reduce