sadmicrowave
sadmicrowave

Reputation: 40892

javascript array for loop i+1 returning undefined

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?

Upvotes: 2

Views: 9799

Answers (6)

Gilgamesh415
Gilgamesh415

Reputation: 43

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

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

Upvotes: 0

mazlix
mazlix

Reputation: 6283

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

Upvotes: 0

Christopher Armstrong
Christopher Armstrong

Reputation: 7953

What about:

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

Upvotes: 0

Jamie Treworgy
Jamie Treworgy

Reputation: 24334

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

Upvotes: 3

maerics
maerics

Reputation: 156394

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.

Upvotes: 2

tofutim
tofutim

Reputation: 23374

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

Upvotes: 1

Related Questions