如何递归地将数组中的每n个元素传递给函数

时间:2018-09-24 21:58:25

标签: javascript

我是编程的新手,过去几天我一直在研究javascript问题。

本质上,我需要编写一个带有三个参数的函数:数组arr,要重复调用的函数fn和值step,该值表示有多少个元素从数组传递到fn。

例如,如果step为3,则将调用fn的前3个元素作为位置参数的arrfn将使用接下来的3个参数再次调用。 fn将继续被调用,直到arr中没有更多元素用作参数为止。如果最后一组参数小于step,请使用剩余的参数调用函数fn

我对递归还很陌生。我看了很多视频,并尝试从教科书中尝试练习问题,这是我遇到的麻烦之一。

任何帮助将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:1)

如果必须使用递归函数,可以尝试

function withRecursion(array, fn, value){
  //take an amount of arguments equal to value by slicing the array
  fn( ...array.slice(0, value) );
  //if the length of array is lower then value this means that this was the last elements of the array
  if(value < array.length){
    //give the function the rest of the array by removing the elements we already used
    withRecursion(array.slice(value, array.length), fn, value); 
  }
}

function test(...args){
  for(var arg of args){
    console.log(arg);
  }
  console.log("test finished");
}

withRecursion([1,2,3,4,5,6,7,8,9,10], test, 3);

答案 1 :(得分:1)

因此,基本上,您需要一个可逐步处理数据的函数:

var arrayToProcess = [1, 2, 3, 4, 5, 6, 7, 8]

function myRecursiveFunction(step, fn, arr) {
  // if the step is greater that the array, process and return
  if (arr.length <= step) {
    fn(arr);
    return;
  }
  // else take out the part of the array that you will process on this step
  myRecursiveFunction(step, fn, arr.slice(step));
  // process the array with only the element belonging to the step
  fn(arr.slice(0, step));
  return;

}

myRecursiveFunction(3, (function(arr) {
  console.log(arr);
}), arrayToProcess);

因此,将要发生的事情是我们将按以下顺序使用这些输入来调用递归函数:

  1. myRecursiveFunction(3, fn, [1,2,3,4,5,6,7,8])

  2. myRecursiveFunction(3, fn, [4,5,6,7,8])

  3. myRecursiveFunction(3, fn, [7,8])

依次将按以下顺序执行输入fn

  1. fn([7,8])

  2. fn([4,5,6])

  3. fn([1,2,3])

我们的停止条件是,如果arr小于步骤arr.length <= step,则我们将继续递归并处理step的前arr个元素。

如果您想了解slice函数的工作原理,可以在这里查看: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice