I have a loop for a coin flipping program that I’m making. the problem is the it seems to be exiting early. Take a look.
$(function() {
$('#rollDice').click(function() {
var e = document.getElementById("diceSides");
var diceSides = e.options[e.selectedIndex].text;
var diceRolls = document.getElementById('rollCount').value;
if (diceRolls.match(/^[\d]*$/ )) {
if (diceRolls == "") {
alert ("Please fill out all forms then try again.");
} else {
$('#diceRollContainer').slideDown('slow');
for (i=0;i<diceRolls;i++) {
var randNum = Math.floor(Math.random()*diceSides)+1;
var rolls = ("You rolled a " + diceSides + " sided die " + diceRolls + " times, and got the numbers ");
rollMinOne = rolls - 1;
if (i == rollMinOne) {
var rolls = (rolls + randNum + ".");
}
var rolls = (rolls + randNum + ", ");
}
alert (rolls);
}
} else {
alert ("Make sure you only enter numbers and no spaces, then try again.");
}
});
});
The problem is that the program is alerting rolls before the for loop seems to be completed. Why is it doing this?
You have several bugs in that code, but the one that explains the behavior you’re seeing is that you reset the value of
rollsevery time through the loop to the initial string.Once you move that line out and you get a closer value, but you are also computing
rollsMinOnefromrolls, rather thandiceRolls, as you intended (this is why choosing good names is so important), meaning that if statement is never true (since a string minus a number is the valueNaN“Not a Number”, which is not equal to anything [even itself!]).Then the only functional (rather than style or design) problem is that you are then appending a value with a comma on the end even if you already added it with a period.
Putting it all together:
Though as the other answers mention, there are easier and faster ways to get the same result, I feel it’s important to understand why code doesn’t work.