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. 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. I've also tried some variants that will return 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. I inserted
TempReduce1=0;
in your code after the line
i=0
and the routine kicked out 9 as one would expect.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.