我在javascript中创建hangman并且我(我认为)成功地从函数中的数组生成了一个随机单词,以检查它是否有效我试图将生成的单词打印到控制台但是它没有似乎在这里工作是我的函数代码
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);
}
提前致谢:)
答案 0 :(得分: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;
};
})();
DEMO: http://jsfiddle.net/bCEFA/1/
您可以声明一个空数组并将值添加到其末尾(使用.push()
),而不是声明具有预定义长度的数组。您也可以将数组声明为:
var gameWordArray = ["monitor", "program", ...];
您试图打印word
(我重命名为getRandomWord
),这是/是一个函数。您可能打算使用console.log(gameWordArray[randno])
,这应该有用。
答案 1 :(得分:1)
以下是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)];
};