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

随机问题生成器仅弹出1道题后退出 无法依次弹出所有问题怎么解决

原代码核心问题
  • 仅执行了1次prompt()调用,没有循环逻辑遍历所有问题,所以只会弹出1次弹窗
  • 分别两次调用randomQuestions()获取题目和答案,两次随机结果可能不一致,会出现题目和答案不匹配的错误
修改方案

先对题库数组做乱序处理(Fisher-Yates 洗牌算法),再遍历乱序后的数组逐个弹出问题,即可实现不重复弹出所有随机问题的效果,修改后代码如下:

let theQuestions = [
     {
        question: "Georgia的首都是什么?", 
        answer:     "atlanta"
     },
     {
        question: "亚特兰大的棒球队叫什么名字?", 
        answer:   "atlanta braves"
     },
     {
        question: "亚特兰大猎鹰队赢过几次总冠军戒指?", 
        answer:   0
     },
     {
        question: "迈阿密的NBA球队叫什么名字?", 
        answer:   "miami heat"
     }
];

// 数组乱序函数
const shuffleArray = (arr) => {
  for (let i = arr.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [arr[i], arr[j]] = [arr[j], arr[i]];
  }
  return arr;
}

// 乱序题库
const shuffledQuestions = shuffleArray([...theQuestions]);

// 遍历弹出所有问题
shuffledQuestions.forEach(item => {
  const userAnswer = prompt(item.question);
  // 答案校验逻辑可按需调整
  if (String(userAnswer).toLowerCase() === String(item.answer).toLowerCase()) {
    alert("回答正确!");
  } else {
    alert(`回答错误,正确答案是:${item.answer}`);
  }
});

如果不需要随机出题顺序,要按原数组固定顺序依次弹出,直接去掉乱序逻辑,遍历原theQuestions数组即可。

内容的提问来源于stack exchange,提问作者myko

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 14:54:02