Javascript Can';我不理解if/for循环的一部分

Javascript Can';我不理解if/for循环的一部分,javascript,Javascript,通过阅读一本名为“headfirstjavascript编程”的书,进入了这个实践示例,但我不太理解其中的某些部分。我应该让它在控制台中显示测试量和最高分数。这是密码 var scores = [60,58,34,69,46,41,50,50,55,64,31,53,60,52,51,66,57,55,58,54,52,55,52,61,54,48,44,52,44,51,54,69,51,61,18,44]; var output; var highScore = 0; for(var

通过阅读一本名为“headfirstjavascript编程”的书,进入了这个实践示例,但我不太理解其中的某些部分。我应该让它在控制台中显示测试量和最高分数。这是密码

var scores = [60,58,34,69,46,41,50,50,55,64,31,53,60,52,51,66,57,55,58,54,52,55,52,61,54,48,44,52,44,51,54,69,51,61,18,44];
var output;
var highScore = 0;



for(var i = 0; i < scores.length; i++){
  output = "Bubble solution #" + i + " score: " + scores[i];
  console.log(output);
  if (scores[i] > highScore){
    highScore = scores[i];
  }
}

console.log("Bubbles tests: " + scores.length);
console.log("Highest bubble score: " + highScore);

目标是知道什么分数最高

  if (scores[i] > highScore){
    highScore = scores[i];
  }
因此,在迭代每个分数时。我们检查当前迭代分数是否高于
highScore
。如果是这样,我们用当前分数更新highscore

迭代1

迭代2

这是存储最高分数的逻辑

在for each In each迭代中,
HighScore
将与当前迭代中的
得分进行比较


如果当前分数大于HighScore,则分数将分配给HighScore变量。

使用for循环遍历列表的所有元素

开始时,将highScore初始化为0

在浏览列表时,如果当前元素值大于highScore中存储的值,则将highScore分配给该元素值,以便在循环结束时,highScore变量中存储的值将是分数列表中的最大值

前。 在第一次循环迭代中,它将是

if(60 > 0) // which is true
    highScore = 60; // so assign value 60 to variable highscore
第二次迭代

if(58 > 60) // which is not true 
   highScore = 58; // so the value of highScore will stay 60
if(34 > 60) // which is not true
    highScore = 34; // so the value of highScore is still 60
第三次迭代

if(58 > 60) // which is not true 
   highScore = 58; // so the value of highScore will stay 60
if(34 > 60) // which is not true
    highScore = 34; // so the value of highScore is still 60
第4次迭代:

if(69 > 60) // which is true
     highScore = 69; // so the value of highScore becomes 69
。 . . 依此类推,直到列表的末尾

基本上,它将从分数列表中获取最大值,并将其保存到highScore变量中


所以最后highScore的值将是69。

所以。。。你到底不明白什么?作业和大于运算符是如何工作的?正如书名所暗示的,头先入的问题在于你错过了聪明的解决方案。你有
分数。长度
,为什么不使用
Math.max.apply(null,分数)
来获得高分,而不是手动循环、检查等?@NiettheDarkAbsol我想这本书的这部分是在解释循环,比如不同的类型,并将其作为一个简单的例子。我的意思是,我们都知道,更聪明的解决方案是只使用以前从未编程过的jQuery。这是第一次。我现在明白了,Weedoze的回答让我大开眼界。是的,是循环,第四章。这是一本适合初学者的书,似乎不是一开始就学习最佳实践。它也有点老了,所以自从它出版以来,事情可能已经改变了。因为它是一种选择算法@尼特赫达克贝尔酒店
if(34 > 60) // which is not true
    highScore = 34; // so the value of highScore is still 60
if(69 > 60) // which is true
     highScore = 69; // so the value of highScore becomes 69