I’m trying to output array elements infinitely. I’ve already found another way to do this, but can you help me understand why the first element doesn’t output in this code after the first iteration of array?
li = [1, 2, 3, 4, 5]
for (i=0; i<li.length; i++) {
console.log(li[i])
if (i+1 == li.length) {
i = 0
}
Expected output:
1
2
3
4
5
1
2
3
4
5
…
Actual output:
1
2
3
4
5
2
3
4
5
…
(1 is present olny in the first loop)
3
Answers
a nice use of the Remainder (%)…
sample code with counter(to avoid infinite loop) :
Inside a for loop, i++ is executed after each iteration completes. Thus, when i reach the index 4 and trigger the if condition, it’s set to 0. Following this, i++ executes, resulting in i becoming 1, leading to a printed value of 2 instead of 1. To address this, you can set i to -1 within the if block to get the desired output.
Code:
Off topic, but if you want to output the array repeatedly, how about a generator:
what is for…of
Careful with "doing something infinitely", your program might do just that, without stopping.
I’ve limited this to 4 loops.