if I have an array myArray which I am looping through:
for(var i=0;i<myArray.length;i++) {
if(myArray[i] == myArray[i+1])
//do something
}
Clearly, myArray[i+1] will fail on the last iteration. Short of testing if i == (myArray.length - 1), is there a clean way to not fail on that if statement and just have it evaluate to false (if myArray[i+1] is out of bounds)?
Why not just iterate up to the (N-2)th item?
if you must iterate till the end, the only way to work in general is to explicitly check if the index is valid. Either
or
However, if you can ensure all items in the array cannot be
undefinedornull, then your original code already works because an index out-of-bound will returnundefined, andundefined == xwill be false unlessxis alsoundefinedornull.