简体   繁体   中英

I am trying to roll the dice 1000 times in JavaScript but my array returms a NaN

So it seems that count[whatever] returns NaN for some reason. Why?

  var i;
  var count = new Array(12);
  for( i = 0; i<999;i++)
   {
     var firstDice = Math.floor(Math.random() * 7);
     var secondDice= Math.floor(Math.random() * 7);
     var total = firstDice + secondDice;
     count[total]++;
   }

   console.log(count[3]);
   for(index=2; index<=12; index++)
   {
     console.log("EL NUMERO "+index+" SALIO "+ count[index]+" VECES MIVIVI");
   }

You are not initializing the array, do:

var count = Array.from({ length: 13 }, () => 0);

or

var count = new Array(13).fill(0);

as suggested in the comments by @ibrahim-mahrir.

Also note that you need 13 elements, not 12 (0, 1, 2 ... 12).

 const count = Array.from({ length: 12 }, () => 0); for(let i = 0; i<999;i++) { const firstDice = Math.floor(Math.random() * 7); const secondDice= Math.floor(Math.random() * 7); const total = firstDice + secondDice; count[total]++; } console.log(count[3]); for(let index=2; index<=12; index++) { console.log("EL NUMERO "+index+" SALIO "+ count[index]+" VECES MIVIVI"); } 

This because when you use new Array(12); you are creating an array of undefined, so when you do ++ on an undefined value you still have an undefined value.

You could take an array with 13 elements, because you have thirteen indices. Then you have to take the values 1 ... 6 as random number for a dice side.

 var i, count = Array.from({ length: 13 }, _ => 0), firstDice, secondDice, total; for (i = 0; i < 999; i++) { firstDice = Math.floor(Math.random() * 6 + 1); secondDice = Math.floor(Math.random() * 6 + 1); total = firstDice + secondDice; count[total]++; } console.log(count[3]); for (i = 2; i <= 12; i++) { console.log("EL NUMERO " + i + " SALIO " + count[i] + " VECES MIVIVI"); } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM