You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在使用Class的JavaScript中实现页面刷新时随机展示题目

页面刷新随机展示题目解决方案

问题分析

你当前代码的核心错误是把随机选题逻辑写在了Question类的构造函数里,而this.text是单个题目的字符串而非数组,this.text[Math.round(Math.random())]只会随机取字符串的第0或第1个字符,完全达不到随机选题的效果。

修正方案

  1. 让Question类仅负责单个题目的数据存储和答案判断,移除构造函数内无效的随机逻辑。
  2. 单独编写函数从题目数组中随机挑选题目。
  3. 页面加载时调用该函数,渲染随机题目。

修改后的完整代码

class Question {
    constructor(text, answers) {
        this.text = text;
        this.answers = answers;
    }

    click(index) {
        return this.answers[index].value;
    }
}

// 补充Answer类(你代码中未定义,需添加)
class Answer {
    constructor(text, value) {
        this.text = text;
        this.value = value;
    }
}

const questions = [
    new Question("Решите неравенство:lg(2x+3)>lg(x-1)",
        [
            new Answer("(-3/2;1)", 0),
            new Answer("(-∞;-4)", 0),
            new Answer("(1;+∞)", 1),
            new Answer("(1;+∞)", 0)
        ]),
    new Question("3 + 78 / 2 = ",
        [
            new Answer("1", 0),
            new Answer("2", 0),
            new Answer("42", 1),
            new Answer("4", 0)
        ]),
    new Question("4 + 98 / 2 = ",
        [
            new Answer("1", 0),
            new Answer("2", 0),
            new Answer("53", 1),
            new Answer("4", 0)
        ]),
    new Question("8 + (-98) / 2 = ",
        [
            new Answer("-41", 1),
            new Answer("2", 0),
            new Answer("3", 0),
            new Answer("4", 0)
        ]),
];

// 随机获取单个题目
function getRandomQuestion() {
    const randomIndex = Math.floor(Math.random() * questions.length);
    return questions[randomIndex];
}

// 页面刷新时渲染随机题目
window.onload = function() {
    const randomQuestion = getRandomQuestion();
    
    // 示例:将题目渲染到页面(需确保页面有对应ID的元素)
    const questionContainer = document.getElementById("question");
    const answersContainer = document.getElementById("answers");
    
    if (questionContainer && answersContainer) {
        questionContainer.textContent = randomQuestion.text;
        answersContainer.innerHTML = "";
        
        randomQuestion.answers.forEach((answer, idx) => {
            const btn = document.createElement("button");
            btn.textContent = answer.text;
            btn.onclick = () => {
                alert(randomQuestion.click(idx) === 1 ? "答对了!" : "答错了!");
            };
            answersContainer.appendChild(btn);
        });
    }
};

说明

  • getRandomQuestion函数通过生成0到题目数组长度-1的随机索引,实现从数组中随机选一个题目。
  • window.onload确保页面加载完成后再执行渲染逻辑,避免DOM元素未加载的问题。
  • 顺便修正了你题目中计算错误的答案,保证题目逻辑正确。

内容的提问来源于stack exchange,提问作者Адиль

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 14:01:35