NiCk Newman
NiCk Newman

Reputation: 1776

How to check when a for loop has finished, inside the loop?

Here is a quick jsfiddle I made to give a better example of my question.

function gi(id){return document.getElementById(id)}

    a= [1,5,1,2,3,5,3,4,3,4,3,1,3,6,7,752,23]


for(i=0; i < a.length; i++){
    /*
    if (WHAT AND WHAT){ What do I add here to know that the last value in the array was used? (For this example, it's the number: 23. Without doing IF==23.

    }
    */

    gi('test').innerHTML+=''+a[i]+' <br>';
}

(the code is also available at https://jsfiddle.net/qffpcxze/1/)

So, the last value in that array is 23, but how can I know that the last value was looped in, inside the loop itself? (Without checking for a simple IF X == 23, but dynamically), if that makes sense.

Upvotes: 8

Views: 25281

Answers (4)

Mr. Alien
Mr. Alien

Reputation: 157374

Write an if statement which compares the arrays length with i

if(a.length - 1 === i) {
    console.log('loop ends');
}

Or you can use a ternary

(a.length - 1 === i) ? console.log('Loop ends') : '';

Demo

Also note that am using - 1 because array index starts from 0 and the length is returned counting from 1 so to compare the array with length we negate -1 .

Upvotes: 14

Rahul Tripathi
Rahul Tripathi

Reputation: 172518

You can try this:

if(i === a.length - 1) {
    //some code
}

Upvotes: 3

FatalError
FatalError

Reputation: 550

You can make the condition in if like this:

function gi(id){return document.getElementById(id)}
a= [1,5,1,2,3,5,3,4,3,4,3,1,3,6,7,752,23];

for(i=0; i < a.length; i++){
  if (i==(a.length-1)){ //give your condition here
     //your stuff
  }
  gi('test').innerHTML+=''+a[i]+' <br>';
}

Upvotes: 3

Vic
Vic

Reputation: 12527

if (i == a.length - 1) {
     // your code here

Upvotes: 5

Related Questions