I’m trying to make a dice roller that can roll multiple die and store the results in an array
Here is the code I am using:
const d4 = Math.floor((Math.random() * 4) + 1)
let dieAmount = 10
let arrayOfResults = []
for (let i = 1; i <= dieAmount; i++) {
arrayOfResults.push(d4)
}
console.log(arrayOfResults)
From my understanding of the for loop arrayOfResults.push(d4) should run 10 times then put each result in a new index but the array that is returned contains 10 indexes of the same value. What is going on here?
3
Answers
The reason of your answer is
Math.random
have already executed and theconst d4
already has a value, so inside the loop you are just pushing same value multiple times but you need a new random number on each iteration, so call theMath.random
function inside the loopYes, but you should call ramdom number in every loop, then only you’ll get defferent defferent ramdom number in every loop like as below:
Your
d4
isconst
and you adding it to the array each time.You could consider using
Array::from()
.A nice shorthand for
Math.random()
could be|
operator.