array ref.length = 7 (0 - 6), and I want to try to match ref[0]['x'] to ref[1]['x'] I am doing this:

   for(var i=0;i<ref.length;i++){
      if( ref[i]['x'] != ref[i+1]['x'] && ref[i+1]['x'].length > 0 )
         //do something
   }

The for loop is iterating all the way to array number 6 then element 6+1 is blank so I get an error on the if statement line saying ref[i+1] is undefined....

is there a better way to do this?

share|improve this question

feedback

5 Answers

up vote 1 down vote accepted
for (var i=0; i<ref.length-1; i++) { // Note the "-1".

This way when you use the index i+1 you're still in bounds.

share|improve this answer
feedback

Better:

for (var i=ref.length-2;i>=0;i--)

Javascript will evaluate the condition on each iteration, so it's generally preferable go backwards instead. With this construct "ref.length" is only evaluated once. Another alternative I like which will perform the same:

var i=ref.length-1;
while (i--) {

}

(Normally you'd be i=ref.length-1 in the first example, and i=ref.length in the second, but you're trying to stay one less than the array length).

share|improve this answer
feedback

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

share|improve this answer
2  
Am I the only one who likes foreplay and maybe a bit of conversation before and after the act? – Jean-François Corbett May 28 '11 at 14:04
feedback

What about:

for(var i=0;i<ref.length-1;i++){
share|improve this answer
feedback

If you just use ref.length-1 won't that solve your problem? I might not fully understand what you're asking.

share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.