Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
166
rated 0 times [  168] [ 2]  / answers: 1 / hits: 16713  / 9 Years ago, sun, august 23, 2015, 12:00:00

I have an array items. I need to make sure that in the current iteration of the loop I can safely call the next item of the array



for(var i = 0; i < items.length; ++i) {

// do some stuff with current index e.g....
item = items[i];


// then do something with item @ i+1
if(items[i+1]) {
//do stuff
}

}


Is this how it is done or if not how/what would be the better way?



P.S. I do not want to do a bound check


More From » qml

 Answers
65

If you want to loop through every element except the last one (which doesn't have an element after it), you should do as suggested:



for(var i = 0; i < items.length-1; ++i) {
// items[i+1] will always exist inside this loop
}


If, however, you want to loop through every element -even the last one-, and just add a condition if there is an element after, just move that same condition inside your loop:



for(var i = 0; i < items.length; ++i) {
// do stuff on every element
if(i < items.length-1){
// items[i+1] will always exist inside this condition
}
}





if(items[i+1]) will return false (and not execute the condition) if the next element contains a falsey value like false, 0, (an empty String returns false).


[#65319] Thursday, August 20, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kristopherw

Total Points: 173
Total Questions: 107
Total Answers: 98

Location: Lesotho
Member since Wed, Jun 2, 2021
3 Years ago
;