我試圖重新定義JavaScript的降低使用遞歸函數。 這是我的嘗試,這是行不通的。如果任何人都可以稍微改變它來使它工作,那將是很棒的,因爲我會更好地理解它。 (這是functional-javascript-workshop的練習)。爲什麼這不是遞歸定義的減少工作(JS)?
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
只是想知道:不'如果(arr.length)'工作?我總是用'如果(arr.length> 0)'... – Danmoreng
你是不是向我們展示了正確的代碼。錯誤發生在第7行在你的'solution.js'中調用'exercise.js'中。 –
@Danmoreng,它測試真值 –