skip to Main Content

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


  1. The reason of your answer is Math.random have already executed and the const 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 the Math.random function inside the loop

    let dieAmount = 10
    let arrayOfResults = []
    
    for (let i = 1; i <= dieAmount; i++) {
      const d4 = Math.floor((Math.random() * 4) + 1)
      arrayOfResults.push(d4)
    }
    console.log(arrayOfResults)
    Login or Signup to reply.
  2. Yes, but you should call ramdom number in every loop, then only you’ll get defferent defferent ramdom number in every loop like as below:

    let dieAmount = 10;
    let arrayOfResults = [];
    
    for (let i = 1; i <= dieAmount; i++) {
        const d4 = Math.floor((Math.random() * 4) + 1);
        arrayOfResults.push(d4);
    }
    console.log(arrayOfResults);
    Login or Signup to reply.
  3. Your d4 is const and you adding it to the array each time.

    You could consider using Array::from().
    A nice shorthand for Math.random() could be | operator.

    const arrayOfResults = Array.from({length:10}, () => 1 + Math.random() * 4 | 0);
    
    console.log(arrayOfResults)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search