对于 Hangman 游戏,我有一些主题(例如:城市和动物)。
当用户选择其中一个主题时,结果应该是所选主题的随机项之一。例如:伦敦或斑马线等。
目前我只有所选主题的随机字母。
const cities = ["New York", "London", "Berlin"]
const animals = ["Alligator", "Alpaca", "Zebra"]
const topicsEl = document.querySelector("#topics")
function randomTopic(){
return topicsEl.value[Math.floor(Math.random()*topicsEl.value.length)]
}
topicsEl.addEventListener("change", function(){
console.log(randomTopic());
})
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
在您现有的代码中,
topicsEl.value将是字符串“cities”或字符串“animals”(因为这些是<select>框中每个选项的值。)。这些不是您在 JavaScript 中定义的全局变量,它们只是 HTML 中包含的字符串。然后,在
randomTopic()中,将该字符串作为数组访问,Javascript 将其解释为您希望将其视为该字符串中的字符数组。这就是为什么您会从单词中获得一个随机字母:"animals"[0]是字母 a,"animals"[1]是字母 n,依此类推。您尝试要做的是从您命名为“城市”和“动物”的数组变量中选择一个随机项目,但您的函数不会尝试触及这些变量,它们只作用于 DOM 中包含的字符串。
因此,您需要添加一个步骤,从
<select>中的字符串值获取到您尝试访问的数组。您已将两个数组定义为全局变量;理论上,这些可以作为
window.cities或window.animals进行访问,因此您可以执行window[topicsEl.value]这将返回您尝试访问的数组....依赖于窗口并不是很好的做法不过,全局变量,所以我鼓励您将这对单独的变量切换到一个对象中以便于访问:const topics = { cities: ["New York", "London", "Berlin"], animals: ["Alligator", "Alpaca", "Zebra"] } const topicsEl = document.querySelector("#topics") function randomTopic() { // find the desired array: let topicArr = topics[topicsEl.value] // return a random element from that array: return topicArr[Math.floor(Math.random() * topicArr.length)] } topicsEl.addEventListener("change", function() { console.log(randomTopic()); })