JavaScript嵌套While循环,无限循环

时间:2016-11-30 21:58:55

标签: javascript loops while-loop nested

所以我试图创建一个循环,将任何数字减少到一个数字。我正在做数学的方法是逐个添加每个数字。在这种情况下,9 + 9 + 9 + 9 + 9 + 9 + 9 + 9 + 9 + 9 + 9 + 9 = 108。我希望它能够贯穿并检查108是否仍然大于9并且直到结果小于9它才会执行。它只是陷入循环中。我也尝试了一些会返回NaN的变种。

<html>
<body>

<h1>Reduce Loop</h1>

<p id="Result"></p>

<script type="text/javascript">
//Defined var start
var Result = 0;
var TempReduce1 = 0;
var LoopTempLength = 0;
var LoopTempString;
var i = 0;
//Defined var end
//The LongNumber variable represents user input
var LongNumber = 999999999999;
//Converts LongNumber to a integer
var LoopTemp = parseInt(LongNumber);
//Check if LoopTemp is greater than 9; it is
while (LoopTemp > 9) {
    //Gets the Length of LoopTemp by converting it to a string and grabbing the length to then convert back to a integer
    LoopTempLength = parseInt(LoopTemp.toString().length);
    //Converts LoopTemp to a string for manipulation
    LoopTempString = LoopTemp.toString();
    i = 0;
    //Check to see if i is less than the length of LoopTempLength
    while (i < LoopTempLength) {
        //Grabs the number in relationship to i, converts it to a integer and added it to TempReduce1
        TempReduce1 += parseInt(LoopTempString.charAt(i));
        i++;
    }
    LoopTemp = TempReduce1;
}   
Result = LoopTemp;

        document.getElementById("Result").innerHTML = Result;

</script>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

帕特里克埃文斯说得对。我插了

ErrorDocument 404 /admin/production/page_403.html

行之后的代码中

TempReduce1=0;

并且例程按照人们的预期踢出了9。