【发布时间】:2020-06-06 07:53:12
【问题描述】:
我有四个数组 - 花、树、小动物和歌曲。
我有四个对应的函数——flower()、tree()、critter() 和 song()。
在上面的每个单独的函数中,我调用了我的 math.random 函数来从特定数组中检索一个随机单词。例如,在我的flower() 函数中,我有:
answer = flowers[Math.floor(Math.random() * flowers.length)];
我发现为了生成随机词,我还需要全局运行我的 math.random 函数。这是我的问题。我不知道在不分配变量的情况下创建 math.random 函数的方法。所以在全球范围内我有这个:
function randomWord() {
answer = songs[Math.floor(Math.random() * songs.length)];
}
所以有时当我在花卉类别中时,我的花卉数组中的一个词会出现 - 但有时会出现一首歌曲,因为我必须将它发布到全球才能让它发挥作用。
我不知道如何修复它,虽然关于数组的 math.floor 函数有很多问题 - 我没有找到任何关于如何处理这样的多个数组的信息。
我想知道对于全局调用的 math.floor 函数,是否可以使用通用词来代替特定的变量词?或者也许是一个 if-else 语句?我被困住了,不胜感激。谢谢。
编辑添加:
@KevinWallis 这是直接从我的代码中粘贴的:
let answer = "";
function randomWord() {
answer = songs[Math.floor(Math.random() * songs.length)];
}
function flower() {
document.getElementById("main").style.display = 'none';
document.getElementById("play").style.display = "block";
answer = flowers[Math.floor(Math.random() * flowers.length)];
word = flowers[answer];
document.getElementById("categoryName").innerHTML = "Types of Flowers";
updateTreePicture();
randomWord();
generateButtons();
guessedWord();
}
更新:我只是想发布修复结果:
function randomWord() {
if (categoryName === 'Flowers') {
answer = flowers[Math.floor(Math.random() * flowers.length)];
} else if (categoryName === 'Trees') {
answer = trees[Math.floor(Math.random() * trees.length)];
} else if (categoryName === 'Critters') {
answer = critters[Math.floor(Math.random() * critters.length)];
} else if (categoryName === 'Songs') {
answer = songs[Math.floor(Math.random() * songs.length)];
}
}
【问题讨论】:
-
你能显示你调用
randomWord()函数的代码吗? -
我不确定我是否理解您的问题,但
return的概念可能会对您有所帮助。 -
根据什么条件选择随机列表?
-
你在哪里调用
flower函数?