如何根据难度过滤题目对象数组并实现题目展示功能?
问题修复:按难度筛选并展示测验题目
你的代码思路没问题,但有几个关键错误导致无法正确展示筛选后的题目,下面是问题点和修正方案:
存在的问题
- 重复声明DOM元素变量:
questionE1、a_answer等被重复获取,会覆盖之前的引用,完全没必要。 - 过滤时机错误:
filteredQuestions初始化时difficultyLevel是空字符串,此时过滤结果为空数组,应该在用户选择难度后再执行过滤。 - 函数调用与判断错误:
getQuestion里把函数pickDifficulty直接和字符串比较,逻辑完全错误,应该先调用函数获取当前选中的难度,再基于难度过滤题目。 - 渲染逻辑未使用过滤后的题目:
displayQuestion还是从原questions数组取题,没有用到筛选后的结果。 - 缺少事件监听:用户勾选难度复选框时,没有触发过滤和重新渲染题目的逻辑。
修正后的完整代码
// 获取DOM元素(只声明一次) const questionEl = document.getElementById("question") const aAnswer = document.getElementById("a-answer"); const bAnswer = document.getElementById("b-answer"); const cAnswer = document.getElementById("c-answer"); const dAnswer = document.getElementById("d-answer"); const submitBtn = document.getElementById("submit"); // 难度复选框元素 const easyDifficulty = document.getElementById("easy-diff"); const mediumDifficulty = document.getElementById("medium-diff"); const hardDifficulty = document.getElementById("hard-diff"); // 全局变量 let currentQuiz = 0; let filteredQuestions = []; const questions = [ { question: `美国最大的城市是哪个?`, a: `芝加哥`, b: `洛杉矶`, c: `波士顿`, d: `纽约`, answer: `d`, difficulty:`hard` }, { question: `地球上最长的河流是哪条?`, a: `亚马逊河`, b: `尼罗河`, c: `黑龙江`, d: `密西西比河`, answer: `b`, difficulty:`medium` }, { question: `地球上最高的山峰是哪座?`, a: `珠穆朗玛峰`, b: `乔戈里峰`, c: `布洛阿特峰`, d: `马纳斯鲁峰`, answer: `a`, difficulty:`easy` }, ]; // 获取当前选中的难度 function getSelectedDifficulty() { if (easyDifficulty.checked) { return "easy"; } else if (mediumDifficulty.checked) { return "medium"; } else if (hardDifficulty.checked) { return "hard"; } return ""; } // 过滤题目并渲染 function filterAndRenderQuestions() { const selectedLevel = getSelectedDifficulty(); // 根据选中难度过滤题目 filteredQuestions = selectedLevel ? questions.filter(question => question.difficulty === selectedLevel) : [...questions]; // 未选中难度时显示所有题目 // 重置当前题目索引 currentQuiz = 0; // 渲染题目 displayQuestion(); } // 渲染题目函数 function displayQuestion() { // 处理过滤后无题目或索引越界的情况 if (!filteredQuestions.length || currentQuiz >= filteredQuestions.length) { questionEl.innerText = "没有对应难度的题目"; aAnswer.innerText = ""; bAnswer.innerText = ""; cAnswer.innerText = ""; dAnswer.innerText = ""; return; } const currentQuestion = filteredQuestions[currentQuiz]; questionEl.innerText = currentQuestion.question; aAnswer.innerText = currentQuestion.a; bAnswer.innerText = currentQuestion.b; cAnswer.innerText = currentQuestion.c; dAnswer.innerText = currentQuestion.d; } // 给难度复选框添加事件监听 easyDifficulty.addEventListener("change", filterAndRenderQuestions); mediumDifficulty.addEventListener("change", filterAndRenderQuestions); hardDifficulty.addEventListener("change", filterAndRenderQuestions); // 初始化渲染所有题目(可选) filterAndRenderQuestions();
修正关键点说明
- 移除重复的DOM变量声明,避免变量覆盖问题。
- 新增
filterAndRenderQuestions函数,整合难度获取、题目过滤、重置索引和渲染的逻辑,每次用户切换难度时调用。 - 给每个难度复选框添加
change事件监听,用户勾选时自动触发筛选和渲染。 - 优化
displayQuestion函数,添加容错处理,避免无题目时出现报错。 - 移除无用的
getQuestion函数,把逻辑整合到更合理的位置。
内容的提问来源于stack exchange,提问作者Huey O'Brien
相关产品推荐
相关产品推荐

