[英]JavaScript Nested While Loop, Loops infinitely
So I'm trying to create a loop that will reduce any number put into it to a single digit. 因此,我正在尝试创建一个循环,该循环会将放入其中的任何数字减少到一位数字。 The way I'm doing my math is adding each number up one by one.
我做数学的方式是将每个数字一一加起来。 In this case 9+9+9+9+9+9+9+9+9+9+9+9=108.
在这种情况下9 + 9 + 9 + 9 + 9 + 9 + 9 + 9 + 9 + 9 + 9 + 9 = 108。 I want it to run through and check that 108 is still greater than 9 and do it till the result is less than 9. It just gets stuck in a loop.
我希望它运行并检查108是否仍大于9并执行直到结果小于9。它只是陷入循环中。 I've also tried some variants that will return NaN.
我还尝试了一些将返回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>
So Patrick Evans has it right. 所以Patrick Evans说对了。 I inserted
我插入
TempReduce1=0;
in your code after the line 在您的代码之后
i=0
and the routine kicked out 9 as one would expect. 例行程序将9踢出了预期。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.