var myArray = ['a','b','c']; var randomItem = myArray[Math.floor(Math.random()*myArray.length)]
Math.random() returns a number between 0 (included) and 1 (not included), which is why this piece of code won’t overshoot by picking a number equal to the array length (reminder: array indexes start at 0, meaning last index is length – 1).
Math.round() is not appropriate as it would result in sometimes hitting a number equal to the array length. Hence the Math.floor().
0 Responses
Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.