skip to Main Content

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


  1. a nice use of the Remainder (%)

    for ( let i = 0 ; ; i = ++i % list.length )
    

    sample code with counter(to avoid infinite loop) :

    let list = [1, 2, 3, 4, 5]
    
    for ( let i = 0, counter = 0
        ; counter < 17
        ; counter++, i = ++i % list.length  // i = (i+1) % lenght
        )
      {           
      document.write( list[i] + ' / ')
      }
    Login or Signup to reply.
  2. 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:

    li = [1, 2, 3, 4, 5]
      for (i=0; i<li.length; i++) {           
            console.log(li[i])
        if (i+1 == li.length) { 
            i = -1 
    }
    }
    
    Login or Signup to reply.
  3. Off topic, but if you want to output the array repeatedly, how about a generator:

    what is for…of

    function* repeat(iterable, times = Infinity) {
      while (times-- > 0) {
        yield* iterable;
      }
    }
    
    for (const nr of repeat([1, 2, 3, 4, 5], 4)) {
      console.log(nr);
    }
    .as-console-wrapper{top:0;max-height:100%!important}

    Careful with "doing something infinitely", your program might do just that, without stopping.
    I’ve limited this to 4 loops.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search