Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print elements from array with recursion in javascript

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?

like image 895
Selin Elibol Avatar asked Jul 28 '26 14:07

Selin Elibol


2 Answers

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)
like image 150
Luis felipe De jesus Munoz Avatar answered Jul 30 '26 03:07

Luis felipe De jesus Munoz


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);
like image 36
PerrinPrograms Avatar answered Jul 30 '26 05:07

PerrinPrograms



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!