2

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?

6 Answers 6

3

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

Sign up to request clarification or add additional context in comments.

Comments

2
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.

Comments

1

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

1 Comment

Am I the only one who likes foreplay and maybe a bit of conversation before and after the act?
0

What about:

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

Comments

0

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

Comments

0

Here's a simple solution. Just count the counter again.

if( ref[i]['x'] != ref[++i]['x'] && ref[++i]['x'].length > 0 )

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.