如何从其他单词列表中随机显示一个单词?

时间:2021-06-16 19:36:36

Ok 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 would randomly pick between all 3 of these names and display it? Would i use math.random()?

我怎么能有一行或几行代码在这三个名字之间随机选择并显示它呢?我会使用math . random()?

1 个解决方案

#1


6  

Since you have a collection of names rather than key value pairs it's better to use an array to store your names rather than a hash.

由于您有一组名称,而不是键值对,所以最好使用数组来存储名称,而不是散列。

With an array, you can use Math.floor and Math.random to generate an index to look up in the names array.

对于数组,您可以使用Math。地板和数学。随机生成要在名称数组中查找的索引。

names[Math.floor(Math.random() * names.length)]

#1


6  

Since you have a collection of names rather than key value pairs it's better to use an array to store your names rather than a hash.

由于您有一组名称,而不是键值对,所以最好使用数组来存储名称,而不是散列。

With an array, you can use Math.floor and Math.random to generate an index to look up in the names array.

对于数组,您可以使用Math。地板和数学。随机生成要在名称数组中查找的索引。

names[Math.floor(Math.random() * names.length)]