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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With