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