William
William

Reputation: 4588

Teaching myself algorithm basics with arrays and for-loops. Why doesn't this for-loop work

The below code is intended to compare an array index with the next index and then print "yay" if the previous index is smaller. I think I understand what I'm doing wrong in that the for loop is thumbing through each index and I'm trying to store the "next" index in a variable before it's looped through it. I'm curious how to solve this. I could google it but I would rather see what people come up with here. I think it's better for learning.

list = [1,2,3,4,5,6,7,8,9];

for(i=0; i<list.length; i++) {
    var small = list[i];
    var large = list[i++];
    if(small<large) {
     document.write("yay");


    }

}

Upvotes: 0

Views: 84

Answers (3)

Allard Stijnman
Allard Stijnman

Reputation: 1344

I just tried this really fast with code-play.com, but the first step in debugging is checking what the actual values of your variables are. I used console.log() for this purpose and with your exact code it results in this:

small: 1
large: 1

small: 3
large: 3

small: 5
large: 5

small: 7
large: 7

small: 9
large: 9

This should give you your first clue as to what is happening here. As you can see each time the values are the same and with each iteration you are skipping a digit. Now when we look at how javascript operators work here you can see this makes sense.

If you would replace this line:

var large = list[i++];

With this line:

var large = list[i+1];

Your problem should be fixed. Note that ++1 also doesn't work, in that case you'll get the following output:

small: 1
large: 2
yay
small: 3
large: 4
yay
small: 5
large: 6
yay
small: 7
large: 8
yay
small: 9
large: undefined

Then the only thing left to do is check the values so you don't increment i above the length of list (this is what causes the large to be undefined in the last iteration) but I'll let you figure that out for yourself, for educational purposes :)

Upvotes: 1

scones
scones

Reputation: 3355

should work like this

l = [1,2,3];
for (i = 0; i l.lenght -1; ++i) {
  if (l[i] < l[i+1]) {
    console.log("meh");
  }
}

Upvotes: 0

Sruti
Sruti

Reputation: 670

When you do a list[i++], value of i is incremented. You are incrementing it again in your for statement. Either assign large to list[i+1] or remove the increment part of the for loop.

Upvotes: 1

Related Questions