3

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?

5
  • 1
    what do you mean by translating to recursive? Commented Apr 9, 2018 at 14:07
  • I want to make myForEach function recursive Commented Apr 9, 2018 at 14:08
  • recursive, you say, from the last value to the first, backwards? 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. 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. Commented Apr 9, 2018 at 14:14

4 Answers 4

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)

Sign up to request clarification or add additional context in comments.

Comments

3

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);

Comments

1

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);

1 Comment

Thank you. This is the answer I'm looking for
0

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.