for the loop


I'm trying to code a javascript dice game, using Math.random () to generate die values ​​and a table to hold the current values ​​of each individual die.
The problems I have are 1), the array ends up containing six numbers, and the loop runs only five times, and 2) I can not understand how to get Math.random () to return different numbers on each roll dice.
Here is the function in question:
 var array = [] function rollDice() { for (var i = 0; i <= 4; i++) { var roll = Math.floor(Math.random() * 6) + 1; array[i] = roll; //array.splice(i, 1, roll); } } 
You can see that 'i' iterates from zero to four in the loop (which equals five loops), and on each loop another random number is generated and inserted into the array at the equivalent place.
Regarding the number of elements in the array: if I run the code as shown above, I will get something like this: [1, 2, 3, 4, 5, undefined].
If I run it using the commented line with the 'splice' function (which should remove the value stored at 'i' and replace it with a new value,) I'll get [1, 2, 3, 4 , 5, 6]. How is it if the loop only works five times?
Regarding the difficulty I have in getting the random numbers to change more surely: I tried the following in my loop ...
 var roll; while (roll === hand[i] || roll === null) { roll = Math.floor(Math.random() * 6) + 1; } 
Read More Articles

0 Comments:

Posting Komentar