tags:

views:

41

answers:

2

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)?

+4  A: 

Why not just iterate up to the (N-2)th item?

for(var i=0;i<myArray.length-1;i++) {
  ...

if you must iterate till the end, the only way to work in general is to explicitly check if the index is valid. Either

for (var i = 0; i < myArray.length; ++ i)
  if (i+1 != myArray.length) {
    ...

or

for (var i = 0; i < myArray.length; ++ i)
  if (!(i+1 in myArray)) {
    ...

However, if you can ensure all items in the array cannot be undefined or null, then your original code already works because an index out-of-bound will return undefined, and undefined == x will be false unless x is also undefined or null.

KennyTM
well I feel dumb now. yea that would definitely work. still is there a graceful way in javascript to have an out of bounds array pointer evaluate to false instead of throwing an error?
bba
...because actually the way my logic is setup (and I'm not saying it can't be refactored) I still need to get to that last iteration (N-1)th item.
bba
Actually `myArray[i+1]` wouldn't fail with an error. It would simply return `undefined`, which compared to `myArray[i]` which would return `false` (unless of course `myArray[i]` is also `undefined`) and everything would be ok.
RoToRa
interesting. so, since contractually the array should never have underfined or null, it wouldn't be poor code to leave it as is then, i guess..even though coming from a Java background it looks dangerous
bba
As T.J. Crowder said above, `myArray[myArray.length]` will evaluate to `undefined`, which is a falsy value. It shouldn't throw an error unless you're then trying to access a property of that array element.
Ryan Kinal
A: 

Look at the jquery source for some inspiration: http://github.com/jquery/jquery/blob/3a0a35288304ab5289a1/src/core.js#L632

hellvinz