Reputation: 7
I am doing recursion for the first time in javascript. I made an array and want it to print out every element however it only printso ut the first element (1)
function loop4(){
arr = [1,2,3,4,5,6,7,8,9,10]
i=0
console.log(arr[i])
i++
if(i<arr.length){
loop4(i)
}
else{
return
}
}
loop4()
This is the code for the program
I have looked at it logically and can see where my mistake was. When the loop starts again "i" is set as 0 therefore infintanly printing out "1" How can I upadte the code in order for it to print out an array with recursion ?
I expect the code to print out the array however i am incapible of doing that so any help would be appreciated
Upvotes: -3
Views: 81
Reputation: 386756
You could hand over the array and the index.
Inside of the function check if the index is greater or equal of the length of the array and return if so. This is the exit condition. (Usually the best place of the exit condition is at start of the function.)
Then show value.
Later call the function again with array and incremented index.
function loop(array, i = 0) {
if (i >= array.length) return; // exit condition
console.log(array[i]); // do something
loop(array, i + 1); // go on with recursion
}
loop([1, 2, 3, 4, 5]);
Upvotes: 2
Reputation: 31
You are passing a parameter, but not reading the value from it. most times when doing recursion, you make 2 versions of a function: The empty call, and the parameterized call. The empty call is just a wrapper function that passes an initial state to the version with parameters.
add a wrapper and initial state and it should work:
function loop4(){
arr = [1,2,3,4,5,6,7,8,9,10];
i=0;
printLoop(i, arr);
}
function printLoop(i, arr) {
if(i<arr.length){
console.log(arr[i]);
i++;
printLoop(i, arr);
} else {
return;
}
}
loop4();
Upvotes: 2
Reputation: 782158
You should pass i
as a parameter, so it doesn't get reset to 0
on each call. You can use a default value for the initial call.
There's no need for else { return }
, since the function returns automatically.
function loop4(i = 0) {
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log(arr[i])
i++
if (i < arr.length) {
loop4(i)
}
}
loop4()
Upvotes: 2