Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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.

like image 411
NiCk Newman Avatar asked May 04 '15 06:05

NiCk Newman


1 Answers

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 .

like image 122
Mr. Alien Avatar answered Sep 27 '22 21:09

Mr. Alien