3

我正在用javascript创建刽子手,我(我认为)成功地从函数中的数组生成了一个随机词,以检查它是否有效我试图将生成的词打印到控制台,但它似乎不是在这里工作是我的函数代码

    var word = function() //Random word is genereated from an array for the user to guess
{
  GameWordArray = new Array(7);
  GameWordArray[0] = "monitor";
  GameWordArray[1] = "program";
  GameWordArray[2] = "application";
  GameWordArray[3] = "keyboard";
  GameWordArray[4] = "javascript";
  GameWordArray[5] = "gaming";
  GameWordArray[6] = "network";
  randno = Math.floor(Math.random() * GameWordArray.length);
  document.write(GameWordArray[randno]);
  console.log(word);
}

提前致谢 :)

4

2 回答 2

3

尝试以这种方式使用它:

var getRandomWord = (function () {
  var gameWordArray = [];
  gameWordArray.push("monitor");
  gameWordArray.push("program");
  gameWordArray.push("application");
  gameWordArray.push("keyboard");
  gameWordArray.push("javascript");
  gameWordArray.push("gaming");
  gameWordArray.push("network");
  return function () {
    var randNum, finalWord;
    randNum = Math.floor(Math.random() * gameWordArray.length);
    finalWord = gameWordArray[randNum];
    return finalWord;
  };
})();

演示:http: //jsfiddle.net/bCEFA/1/

与其声明一个具有预定义长度的数组,不如声明一个空数组并在其末尾添加值(使用.push())。你也可以像这样声明数组:

var gameWordArray = ["monitor", "program", ...];

您正在尝试打印word(我将其重命名为getRandomWord),这是/是一个函数。您可能打算使用console.log(gameWordArray[randno]),它应该可以工作。

于 2013-04-17T16:43:43.017 回答
3

这是关于jsfiddle的示例

var words = ["monitor", "program", "application", "keyboard", "javascript", "gaming", "network"];

var word = words[Math.floor(Math.random() * words.length)];

console.log(word);

document.getElementById("word").textContent = word;

并让它直接适合您提供的代码:

var getRandomWord = function () {
    return words[Math.floor(Math.random() * words.length)];
};
于 2013-04-17T16:47:28.070 回答