简体   繁体   English

使用数组和for循环教自己算法基础知识。 为什么这个for循环不起作用

[英]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. 下面的代码用于比较数组索引和下一个索引,然后如果前一个索引较小则打印“yay”。 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. 我想我明白我做错了,因为for循环正在翻阅每个索引,而我试图将“next”索引存储在一个变量中,然后才循环通过它。 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. 当您执行列表[i ++]时,i的值会递增。 You are incrementing it again in your for statement. 您在for语句中再次递增它。 Either assign large to list[i+1] or remove the increment part of the for loop. 分配大到列表[i + 1]或删除for循环的增量部分。

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. 我只是用code-play.com快速尝试了这一点,但调试的第一步是检查变量的实际值是什么。 I used console.log() for this purpose and with your exact code it results in this: 我为此目的使用了console.log(),并使用您的确切代码导致:

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. 现在,当我们看看javascript运算符如何在这里工作时您可以看到这是有道理的。

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: 请注意,++ 1也不起作用,在这种情况下,您将获得以下输出:

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 :) 那么剩下要做的唯一事情就是检查值,这样你就不会在列表长度之上增加i(这就是导致在上一次迭代中未定义大值的原因)但是我会让你自己解决这个问题,用于教育目的:)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM