Background
I'm just learning JavaScript and I thought that a good way to start was to code my own dice roller for an RPG I play. For this game you roll a handful of six-sided dice where each 4 or 5 is worth one success and each 6 is worth 2 successes.
I have a function that rolls the dice and passes the rolls, via an array, to another function that HTML-ifies it for display on the webpage.
The Code
In order to roll the dice, I have what I think is the standard dice roller function (the sides
variable is because sometimes you can roll dice that have sides other than 6, so I made the function usable for all dice rolls):
function rollDice(sides) {
return Math.floor(Math.random()*sides) + 1;
}
Because the number of dice you roll varies, my main function calls this rollDice()
function a number of times and puts each result in an array.
This is the main function, where number
is the number of dice to roll:
function dice(number) {
let results = [];
for (i=0; i<number; i++){
results.push(rollDice(6));
}
return results;
}
However, I have since learned of the do…while
loop, and have managed to refactor it thusly:
function dice(number) {
let results = [];
do {
results.push(rollDice(6));
} while (results.length < number)
return results;
}
The Actual Question
Which loop is more 'correct' or best practice to use? for
or do…while
?