Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to build an array that fills each position with a dice roll

Here is my current code:

const diceRoll = Math.trunc(Math.random() * 6) + 1;
const diceRollArr = Array.from ({length: 4}, (_, i) => diceRoll[i]);

console.log(diceRollArr); //Returns: (4)[undefined, undefined, undefined, undefined]

Can’t wrap my head around what I’m missing. If I do:

const diceRoll = Math.trunc(Math.random() * 6) + 1;
    const diceRollArr = Array.from ({length: 4}, (_, i) => diceRoll);

It will generate the same dice roll for the given array length, so I need a way to do a dice roll for each index position. Any help would be greatly appreciated, thanks!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are accessing diceRoll as an array when it’s a variable. Also you need diceRoll to be a function and call it at every iteration

const diceRoll = () => Math.trunc(Math.random() * 6) + 1;
const diceRollArr = Array.from ({length: 4}, (_, i) => diceRoll(i));

console.log(diceRollArr);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading