Learn Javascript-Loops-Lesson 6


#1
var cards = ['Diamond', 'Spade', 'Heart', 'Club'];

var currentCard = 'Heart';

while (currentCard !== 'Spade') {
  console.log(currentCard);

  var randomNumber = Math.floor(Math.random() * 4);

  currentCard = cards[randomNumber];
}

console.log('Found a Spade!');

This is the code given as the solution. I have one problem with it. Given the randomNumber variable the program will generate a number anywhere between 1 and 4 and round down to the nearest integer. That number will correspond to an index in an array. But if randomNumber returns as exactly 4, what happens?-since there is no value in the array that corresponds to the fourth index? There are four parameters in the array but no fourth index because it starts counting from zero. Why does this not return an error?


#2

because Math.random() generates a number between 0 and 1 (0 and 1 exclusive), so the smallest number is something like 0.00000000000001 or so. So the biggest number is 0.9999999999999 or so. 0.99 * 4 will give 3.something, it will never give 4


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.