admin管理员组

文章数量:1335404

Array.prototype.myForEach = function(element) {
  for (var i = 0; i < this.length; i++) {
    element(this[i], i, this);
  }
};

var forArr = ['8', '17', '25', '42','67'];
forArr.myForEach(function(exm){
  console.log(exm);
});

Array.prototype.myForEach = function(element) {
  for (var i = 0; i < this.length; i++) {
    element(this[i], i, this);
  }
};

var forArr = ['8', '17', '25', '42','67'];
forArr.myForEach(function(exm){
  console.log(exm);
});

I wrote in the form. Can you help in translating this into recursive?

Share Improve this question edited Apr 9, 2018 at 14:05 Durga 15.6k2 gold badges30 silver badges54 bronze badges asked Apr 9, 2018 at 14:03 Selin ElibolSelin Elibol 1113 silver badges11 bronze badges 5
  • 1 what do you mean by translating to recursive? – Calvin Nunes Commented Apr 9, 2018 at 14:07
  • I want to make myForEach function recursive – Selin Elibol Commented Apr 9, 2018 at 14:08
  • recursive, you say, from the last value to the first, backwards? – Calvin Nunes Commented Apr 9, 2018 at 14:09
  • No. It will be from the beginning to the end, but the function will call itself in order to call the first element of the array and the second element. I can give hope. – Selin Elibol Commented Apr 9, 2018 at 14:13
  • really unclear how recursion would work with a flat array. Usually you would use recursion for nested arrays. – epascarello Commented Apr 9, 2018 at 14:14
Add a ment  | 

4 Answers 4

Reset to default 3

var forArr = ['8', '17', '25', '42','67'];

var recursive_function = function(array){
  if(array.length > 0){
    console.log(array[0]);
    recursive_function(array.slice(1))
  }
}

recursive_function(forArr)

Array.shift will do the trick here

var forArr = ['8', '17', '25', '42', '67'];

function recursivearray(array) {
  if (array.length > 0) {
    console.log(array.shift());
    recursivearray(array);
  }
}
recursivearray(forArr);

You could use a function call with an additional parameter for the actual index.

Array.prototype.myForEach = function (fn, thisArg, i = 0) {
    if (!(i in this)) {
        return;
    }
    fn.bind(thisArg)(this[i], i, this);
    this.myForEach(fn, thisArg, i + 1);
};

function showValues(v, i, a) {
    console.log(v, i, JSON.stringify(a));
}

[99, 100, 101, 102].myForEach(showValues);

This code should print elements with recursion in JS:

var foo = ["8", "17", "25", "42", "67"];
const product = (arr) => {
  if (!arr.length) return 1;
  return product(arr.slice(1)) * arr[0];
};
console.log(product(foo));

本文标签: How to print elements from array with recursion in javascriptStack Overflow