-6

对于我高中的计算机编程课程,我需要为学期末制作一个程序。目前我正在考虑做一个 Black Ops 2 加载生成器,为此我需要在 Javascript 中生成随机单词。我希望能够从单词列表中生成一个单词。所以如果我的单词列表是这样的:

Horse,
Pig,
Dog,
Cat,
Parrot,
Iguana,

然后我希望能够随机生成其中一个,然后将其显示在文本框中。

4

2 回答 2

6
  1. Put these items in an array. var array = ["Horse", "Pig", "Dog", "Cat", "Parrot", "Iguana"];
  2. Generate a random number. var randInt = randomGenerator(0, array.length - 1); ( Generating random whole numbers in JavaScript in a specific range? )
  3. Use the random number to get an item from the array. var item = array[randInt];
  4. Use document.getElementById to get the textbox you want, and use .value = to set the textbox's value. var textbox = document.getElementById("textbox_id").value = randInt;
于 2013-04-15T14:28:42.487 回答
2

You just use Math.random() and index into the array of words.

var words = ['Horse',
'Pig',
'Dog',
'Cat',
'Parrot',
'Iguana'
];
function randomWord(arr) {
    return arr[Math.floor(Math.random() * arr.length)];
}

for(var x=0; x<20; x++)
    console.log(randomWord(words));
于 2013-04-15T14:30:06.900 回答