简体   繁体   English

如何编写递归化简函数?

[英]How to write a recursive reduce function?

I am trying to write a reduce function using recursion. 我正在尝试使用递归编写一个reduce函数。 I am learning recursion and its part of an exercise so Im trying to understand what is it that doesn't work in my code. 我正在学习递归及其练习的一部分,所以我试图了解它在我的代码中不起作用。 Happy about any help! 很高兴获得任何帮助! Ps. 附言 its suppose to start from the end of the array (so for example yeh becomes hey) 它假设从数组的末尾开始(例如,yeh变为hey)

var strings = function(previous,current) {
    return previous+current;
};

function reducing(arr,start,func) {

    if (arr.length == 0) {
        return start;
    }
    else if (arr.length == 1) {
        return arr[0];
    }
    else {
        return func(start,arr[arr.length-1]) + reducing(arr.slice(1),start,func);
    }
}

reducing(['y','e','h'],'',strings)

This could be the problem, instead of reducing(arr.slice(1),start,func) try reducing(arr.slice(0, arr.length-1),start,func) as below: 这可能是问题所在,而不是用reduce(arr.slice(1),start,func)来尝试reduce(arr.slice(0,arr.length-1),start,func),如下所示:

function reducing(arr,start,func) {
  if (arr.length == 0) {
     return start;
  }
  else if (arr.length == 1) {
     return arr[0];
  }
  else {
    return func(start, arr[arr.length-1]) + reducing(arr.slice(0, arr.length -1),start,func);
 }
}

Another solution: 另一个解决方案:

const reduce = (arr, fn, initial) =>
  (reduceAux = (index, value) =>
    index > arr.length-1
      ? value
      : reduceAux(index+1, fn(value, arr[index], index, value))
  )(0, initial);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM