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?

asked May 27, 2011 at 18:32

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

answered May 27, 2011 at 18:35
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.

answered May 27, 2011 at 18:34

Comments

1

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

answered May 27, 2011 at 18:33

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++){
answered May 27, 2011 at 18:35

Comments

0

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

answered May 27, 2011 at 18:36

Comments

0

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

if( ref[i]['x'] != ref[++i]['x'] && ref[++i]['x'].length > 0 )
Java Devil
11.1k7 gold badges37 silver badges50 bronze badges
answered Aug 25, 2013 at 23:09

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.