Review Algorithmic Thinking by Building a Dice Game - Step 3

Tell us what’s happening:

As per the instructions, my code is generating a 5 digit array. After that, with this logic, the code only reflects the last digit of the array when I click “Roll the dice” button . Can anybody help to rectify the issue? For Example, diceValuesArr = [6,5,2,2,3], then all the five boxes will show number 3, rather than displaying a corresponding number in each box.

Your code so far

<!-- file: index.html -->

/* file: styles.css */

/* file: script.js */
// User Editable Region

rollDiceBtn.addEventListener("click", () => {
  diceValuesArr = Array.from({ length: 5 }, () => Math.floor(Math.random() * 6 + 1));
console.log(diceValuesArr);

  listOfAllDice.forEach((die) => {
    for (let i = 0; i < diceValuesArr.length; i++) {

      die.innerText = `${diceValuesArr[i]}`
    }

  })

});

// User Editable Region

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36

Challenge Information:

Review Algorithmic Thinking by Building a Dice Game - Step 3

your code is needlessly complex.
Once you created the random numbers, you just needed to iterate over the elements (which you are doing) and place each number into the text content. The inner for-loop is updating the textContent 5 times (on each html element) so only the last update (the 3) is going to end up being seen.

When I removed the inner for loop, it reflects the whole array in all the boxes. I’m not sure how should I iterate so that it only display a corresponding number .

you have to display the appropriate element of the random dice array as you loop over the element boxes.
You wrote some complex code to create the random numbers, so it is hard to believe that you don’t know how to create a simple loop over the input elements and set one value from the dice (in order) to it.

Click below if really necessary:

You need to use bracket notation to access a single item in the diceValuesArr but the index should come from the forEach callback method. Look it up on MDN to see how to use forEach with an index param or just simply use a a counter variable that counts from 0 to 5.

1 Like

Hey, thanks for the help. Indeed it’s really simple. I was thinking unnecessarily far. Thanks again.

1 Like