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");
}
}
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.