Hangman游戏中选择主题后无法获取对应分类随机条目问题
解决Hangman游戏主题随机条目获取问题
问题原因
你当前的代码中,topicsEl.value返回的是选中选项的字符串值("cities"或"animals"),而randomTopic函数正在对这个字符串取随机字符,而非访问对应的主题数组,所以才会得到主题名称的随机字母。
修正后的代码
JavaScript 部分
const topicLists = { cities: ["New York", "London", "Berlin"], animals: ["Alligator", "Alpaca", "Zebra"] } const topicsEl = document.querySelector("#topics") function randomTopic(){ // 获取选中主题对应的数组 const selectedList = topicLists[topicsEl.value] // 从数组中返回随机元素 return selectedList[Math.floor(Math.random() * selectedList.length)] } topicsEl.addEventListener("change", function(){ console.log(randomTopic()); })
HTML 部分(规范语法)
<div class="select"> <label for="topics">Choose a topic:</label> <select id="topics"> <option value="cities">Cities</option> <option value="animals">Animals</option> </select> </div>
关键修正点
- 使用对象
topicLists将主题名称和对应数组绑定,通过topicLists[topicsEl.value]可以直接获取选中主题的条目数组。 - 计算随机索引时,基于选中数组的长度
selectedList.length生成,确保索引在数组的有效范围内,不会出现越界错误。 - 给HTML中
<option>的value属性添加引号,符合标准HTML语法规范。
内容的提问来源于stack exchange,提问作者EmRe Cos
相关产品推荐
相关产品推荐

