2017-04-11 111 views
0

這是我的代碼:For循環不存儲變量?

<html> 
<head> 
    <title>Temperature Information</title> 
</head> 
<body> 
    <script> 
    //declare variables 
     var BR = "<br />"; 
     var ES = " "; 
     var counter; 
     var temp = [counter]; 
     var max = 0; 
     var min = 0; 
     var tempTot; 
     var tempAve; 
     //loop 
     for (counter = 1; counter <= 5; counter++) { 
      tempTot = tempTot + temp[counter]; 
      temp[counter] = prompt("Enter the temperature for noon on day #" + counter,ES); 
      temp[counter] = parseFloat(temp[counter]); 
      if (temp[counter] == temp[1]){ 
       temp[counter] = max; 
       temp[counter] = min; 
      }else if (temp[counter + 1] > temp[counter] && temp[counter] != temp[1]){ 
       temp[counter] = max; 
      }else if (temp[counter + 1] < temp[counter] && temp[counter] != temp[1]){ 
       temp[counter] = min; 
      } 
      tempTot = tempTot + temp[counter]; 
     } 
     tempAve = tempTot/4; 
     //display info 
     document.write("The average temperature is: " + tempAve + BR); 
     document.write("The maximum temperature is: " + max + BR); 
     document.write("The minimum temperature is: " + min + BR); 
    </script> 
</body> 

它應該承擔的溫度信息5天,顯示平均值,最大值和分鐘。一切似乎運行良好,但它只顯示結果與null。難道我做錯了什麼?我覺得我對這件事太想了。

+0

'var temp = [counter];'應該做什麼? – gsc

+0

你的代碼有很多錯誤。 – MultiplyByZer0

+3

您正在通過'temp [counter + 1]'訪問尚未填充的溫度值。那些將是'未定義',當你將它與一個數字進行比較時,它將強制轉換成'NaN'。涉及'NaN'的比較總是錯誤的。此外,雖然它不會導致上述代碼中的問題,但數組索引從0開始,而不是從1開始。我建議逐步瀏覽內置於瀏覽器中的調試器中的代碼,觀察各種變量的值等等。這就像在黑暗的房間裏打開燈光,直到後來纔開始學習。初學者需要調試器。 :-) –

回答

0

您的代碼中存在一些小錯誤。使用browser's debugger或使用console.log來檢查狀態將幫助您找出錯誤。例如,您的temp數組的0元素是undefined,所以當您對它進行數學運算時,會發生不好的事情;)。另外,一旦你擁有了所有的元素,而不是「實時地」執行它,處理你的數組更容易。最後,總是檢查JavaScript庫是否可以爲你(Math.min)做些什麼而不是寫它......

哦,我也把你的代碼放到它自己的函數中。如果你在調試器中查看代碼,你會發現你的變量現在都很好地包含在它們自己的範圍內,而不是與全局範圍混合在一起。

<html> 
<head> 
    <title>Temperature Information</title> 
</head> 
<body> 
    <script> 
     var tempInformation = function() { 
     var BR = "<br />"; 
     var ES = " "; 
     var temp = []; 

     for (var counter = 0; counter < 5; counter++) { 
      var input = prompt("Enter the temperature for noon on day #" + (counter + 1), ES); 
      temp[counter] = parseFloat(input); 
     } 

     var sum = temp.reduce((previous, current) => current += previous); 
     var avg = sum/temp.length; 

     document.write("The average temperature is: " + avg + BR); 
     document.write("The maximum temperature is: " + Math.max.apply(null, temp) + BR); 
     document.write("The minimum temperature is: " + Math.min.apply(null, temp) + BR); 
     } 

     tempInformation(); 
    </script> 
</body> 
+1

非常感謝。這比我想象的要簡單得多 – Dez