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

React开发测验应用:如何随机同时展示全部5道题目

实现随机展示全部测验题目的方案

你当前的代码仅能抽取单个随机题目,要实现同时展示全部5道随机排序的题目,核心是对题目数组做洗牌处理,而非仅获取单个元素。这里推荐使用高效且公平的Fisher-Yates洗牌算法来实现:

1. 实现洗牌函数

// Fisher-Yates 洗牌算法,生成随机排序的数组副本
const shuffleArray = (array) => {
  const shuffled = [...array];
  for (let i = shuffled.length - 1; i > 0; i--) {
    const randomIndex = Math.floor(Math.random() * (i + 1));
    // 交换当前元素与随机位置元素
    [shuffled[i], shuffled[randomIndex]] = [shuffled[randomIndex], shuffled[i]];
  }
  return shuffled;
};

2. 在组件中初始化随机排序的题目数组

// 初始化状态为洗牌后的题目数组
const [shuffledQuestions, setShuffledQuestions] = useState(() => shuffleArray(questions));

3. 渲染全部随机题目

之后直接遍历shuffledQuestions数组,就能同时展示所有5道随机顺序的题目:

return (
  <div className="quiz-container">
    {shuffledQuestions.map((question, index) => (
      <div key={index} className="question-card">
        <h3>题目 {index + 1}</h3>
        <p>{question.content}</p>
        {/* 渲染选项等内容 */}
      </div>
    ))}
  </div>
);

注意事项

  • 使用[...array]复制原数组,避免直接修改原始的questions数组,保证数据的不可变性。
  • Fisher-Yates算法能确保每个元素的随机分布是公平的,对于5道题的小数组性能完全足够。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 00:05:00