对于循环不存储变量?

时间:2017-04-11 16:39:41

标签: javascript

这是我的代码:

<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。难道我做错了什么?我觉得我在想这个太多了。

1 个答案:

答案 0 :(得分: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>