【发布时间】:2018-08-18 02:19:19
【问题描述】:
尝试编写一个可以过滤掉任何重复项的 reduce 函数。我知道还有其他方法可以解决这个问题,但我正在尝试练习递归函数。
function addToSet(a, b) {
a.add(b);
return a;
}
let set = new Set;
function reduce([head, ...last], fn, init) {
if (head === undefined) return init;
return fn(fn(init, head), reduce(last, fn, init))
}
const a = reduce([1, 2, 4, 6, 4, 3, 1, 2, 5, 1, 3, 4, 5, 7, 7], addToSet, set)
console.log(a)
// in node this returns // Set { 1, 2, 4, 6, 3, 5, 7, [Circular] }
我读到循环意味着对象是自引用的?但我不确定我是否完全理解这在 Set 的上下文中意味着什么。为什么我会遇到这个问题,我该如何解决? 非常感谢你们的时间!
【问题讨论】:
标签: javascript node.js function recursion circular-reference