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

如何从数组中无重复随机选取对象用于测验项目开发

从对象数组中随机选取测验问题的解决方案

场景1:随机选取单个问题

直接利用Math.random()生成合法随机索引,快速获取数组里的随机问题对象:

// 假设你的问题数组是 questions(包含30个对象)
const randomSingleQuestion = questions[Math.floor(Math.random() * questions.length)];

原理:Math.random()返回0到1之间的随机浮点数,乘以数组长度(30)后得到0到30(不含)的数值,Math.floor()取整后得到0-29的合法索引,对应数组里的随机对象。


场景2:随机选取多个不重复的问题

如果需要选多个且不重复的问题,用Fisher-Yates洗牌算法最稳妥,能保证每个问题被选中的概率均等,还不会修改原数组:

// 参数1:你的问题数组;参数2:需要选取的问题数量
function pickRandomQuestions(questions, numToPick) {
  // 复制原数组,避免破坏原数据
  const shuffledArray = [...questions];
  let currentIdx = shuffledArray.length;
  let randomIdx;

  // 洗牌过程
  while (currentIdx > 0) {
    randomIdx = Math.floor(Math.random() * currentIdx);
    currentIdx--;
    // 交换当前元素和随机选中的元素
    [shuffledArray[currentIdx], shuffledArray[randomIdx]] = 
      [shuffledArray[randomIdx], shuffledArray[currentIdx]];
  }

  // 返回前numToPick个洗牌后的元素
  return shuffledArray.slice(0, numToPick);
}

// 示例:从30个问题里随机选10个不重复的
const selectedQuestions = pickRandomQuestions(yourQuestionsArray, 10);

如果你的需求是打乱整个问题数组的顺序(比如让测验题随机排序),直接使用洗牌后的数组即可,无需slice截取。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 19:45:40