How to display a word randomly from a list of other words?

So I have an array of names like this

var names = ["Bob", "Aaron", "John"]; 

How would I have a line or lines of code that randomly select between all three of these names and display them? Would I use math.random ()?

+5
source share
1 answer

Since you have a collection of names, not key pairs, it is better to use an array to store your names, not a hash.

With an array, you can use Math.floor and Math.random to generate an index to search in an array of names.

 names[Math.floor(Math.random() * names.length)] 
+6
source

All Articles