点击按钮从JSON文件获取随机单词功能故障求助
从JSON文件加载随机单词的问题修复
你写的代码里有几个问题,导致功能无法正常运行:
fetch是异步操作,按钮点击事件可能在JSON数据加载完成前就触发,此时words还是空数组,会导致计算随机索引出错- 你的JSON结构是外层包含
words数组的对象,但你直接把整个响应数据赋值给了words,导致words变成了一个带words属性的对象,而非数组 - 数组里的元素是纯字符串(比如"apple"),不是带
word属性的对象,所以words[randomIndex].word会报错 - 没有把选中的单词显示到
result-box里 - 没处理单词被取完后的情况
修正后的代码
JavaScript代码(words.js)
const subButton = document.getElementById('generate-word'); const resultBox = document.getElementById('result-box'); let words = []; // 加载JSON单词文件 fetch('words.json') .then(response => { // 检查请求是否成功 if (!response.ok) { throw new Error('加载单词文件失败'); } return response.json(); }) .then(data => { // 正确提取JSON中的单词数组 words = data.words; // 数据加载完成后启用按钮,避免提前点击 subButton.disabled = false; }) .catch(error => { console.error(error); resultBox.textContent = '加载单词列表失败,请检查文件路径'; }); // 按钮点击事件逻辑 subButton.addEventListener('click', () => { // 处理单词耗尽的情况 if (words.length === 0) { resultBox.textContent = '所有单词已用完!'; subButton.disabled = true; return; } // 生成随机索引 const randomIndex = Math.floor(Math.random() * words.length); // 获取选中的单词(数组元素是字符串,直接取值即可) const selectedWord = words[randomIndex]; // 将单词显示到页面 resultBox.textContent = selectedWord; // 从数组中移除已选中的单词 words.splice(randomIndex, 1); });
HTML代码
<div> <!-- 初始禁用按钮,防止数据未加载时误触 --> <button id="generate-word" disabled>Generate!</button> <div id="result-box"></div> </div> <script src="words.js"></script>
words.json文件(无需修改)
{ "words": [ "apple", "banana", "orange", "coconut", "cantaloupe", "shoe" ] }
关键修正说明
- 异步加载处理:初始禁用按钮,等JSON数据加载完成后再启用,彻底避免提前点击导致的空数组错误;同时增加了请求失败的错误提示。
- JSON数据解析修正:将
words = data改为words = data.words,正确提取出数组格式的单词列表。 - 单词取值修正:直接使用
words[randomIndex]获取单词,因为数组元素本身就是字符串,不需要访问word属性。 - 添加显示逻辑:通过
resultBox.textContent把选中的单词展示到页面上,实现核心的交互反馈。 - 空数组处理:当所有单词被取完后,给出提示并禁用按钮,提升用户体验。
内容的提问来源于stack exchange,提问作者Metalois
相关产品推荐
相关产品推荐

