gpt4 book ai didi

javascript - 为什么这个 reduce working (JS) 的递归定义不是?

转载 作者:行者123 更新时间:2023-12-03 13:17:47 24 4
gpt4 key购买 nike

我正在尝试使用递归函数重新定义 Javascript 的 reduce。这是我的尝试,这是行不通的。如果任何人都可以稍微改变它以使其工作,那就太好了,因为我会更好地理解它。 (这是 functional-javascript-workshop 中的练习)。

function reduce(arr, fn, initial) {
if (arr.length) {
var newArr = arr.slice(1, arr.length);
return reduce(newArr, fn, fn(arr[0]));
} else {
return initial;
}
}

module.exports = reduce

它给了我以下神秘的错误消息,我不知道如何解释:

/usr/local/lib/node_modules/functional-javascript-workshop/exercises/basic_recursion/exercise.js:13
prev[curr] = ++prev[curr] || 1
^

TypeError: Cannot create property 'undefined' on string 'exercitation'
at /usr/local/lib/node_modules/functional-javascript-workshop/exercises/basic_recursion/exercise.js:13:29
at reduce (/home/david/node-school/functional-workshop/solution.js:7:28)
at /usr/local/lib/node_modules/functional-javascript-workshop/exercises/basic_recursion/exercise.js:12:10
at obtainResult (/usr/local/lib/node_modules/functional-javascript-workshop/exercises/runner.js:100:21)
at Exercise.<anonymous> (/usr/local/lib/node_modules/functional-javascript-workshop/exercises/runner.js:66:27)
at next (/usr/local/lib/node_modules/functional-javascript-workshop/node_modules/workshopper-exercise/exercise.js:188:19)
at /usr/local/lib/node_modules/functional-javascript-workshop/node_modules/workshopper-exercise/exercise.js:195:7
at Exercise.<anonymous> (/usr/local/lib/node_modules/functional-javascript-workshop/exercises/runner.js:34:5)
at next (/usr/local/lib/node_modules/functional-javascript-workshop/node_modules/workshopper-exercise/exercise.js:188:19)
at /usr/local/lib/node_modules/functional-javascript-workshop/node_modules/workshopper-exercise/exercise.js:195:7

最佳答案

您需要更新累加器:

function reduce(arr, fn, acc) {
if (arr.length) {
var newArr = arr.slice(1, arr.length);
acc = fn(arr[0], acc)
return reduce(newArr, fn, acc);
} else {
return acc;
}
}

console.log(reduce([1,2,3], (val, sum) => sum + val, 0))

关于javascript - 为什么这个 reduce working (JS) 的递归定义不是?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43613803/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com