You need to enable JavaScript to run this app. JavaScript如何按指定概率从多数组抽取随机对象存入临时数组
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript如何按指定概率从多数组抽取随机对象存入临时数组

原生JS实现指定概率的随机抽取逻辑

实现思路

不需要引入第三方工具,用原生API就能完成,步骤很直接:

  • 先生成0~1区间的随机数,用这个数判断走哪个抽取分支
  • 随机数小于0.8时,按规则把fruits、car合并成待抽取的对象池
  • 随机数大于等于0.8时,直接用books数组当待抽取的对象池
  • 在选中的对象池里生成随机索引取出对应对象,最后把对象塞进tempArray就行

可直接运行的代码

// 题目给定的初始数组
const fruits = [
  {name: "Banana"}, 
  {name: "Apple"}, 
  {name: "Peach"}
]

const car = [
  {name: "Audi"}, 
  {name: "Bentley"}
]

const books = [
  {name: "Alice in wonderland"}, 
  {name: "Deep in the dark"}, 
  {name: "Hunting Show"}
]

const tempArray = []

// 单次抽取逻辑
function pickRandomItem() {
  const prob = Math.random()
  let targetPool

  // 80%概率走fruits/car的抽取分支
  if (prob < 0.8) {
    targetPool = [...fruits, ...car]
  } else {
    // 20%概率走books的抽取分支
    targetPool = books
  }

  // 生成池内的合法随机下标,避免越界
  const randomIdx = Math.floor(Math.random() * targetPool.length)
  const item = targetPool[randomIdx]

  tempArray.push(item)
}

注意事项

  • 调整概率比例的时候,只需要修改if判断里的0.8这个阈值就行,比如改成0.7就对应70%/30%的比例,不需要改动其他逻辑
  • 把fruits和car合并成同一个抽取池的写法,和“先随机选择从fruits还是car中抽取、再在对应数组内取元素”的效果完全等价,代码更简洁没有冗余
  • 索引用Math.floor向下取整,是因为Math.random() * 数组长度的最大值刚好等于数组长度,取整后就能匹配数组从0开始的下标规则,不会出现取到undefined的问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.21 09:06:05