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

JavaScript中如何根据对象的整型值将对应键名多次推入数组

JavaScript 加权抽奖结果数组生成方案

实现思路

遍历权重对象的每一组「结果名称-出现次数」配置,为每个结果生成对应数量的重复元素,最后合并所有元素得到最终的outcomes数组,完全兼容动态的权重配置,不管有多少种抽奖结果、各结果的次数怎么调整都适用。


代码实现

写法1:逻辑直白,适合新手理解

const weights = {
  'win': 5,
  'loss': 10,
  'tie': 3
}
const outcomes = []

// 遍历权重对象的所有结果项
for (const result in weights) {
  const appearCount = weights[result]
  // 按次数重复推入结果
  for (let i = 0; i < appearCount; i++) {
    outcomes.push(result)
  }
}

// 验证:最终数组长度为 5+10+3=18
console.log(outcomes.length)

写法2:简洁语法实现

const weights = {
  'win': 5,
  'loss': 10,
  'tie': 3
}
// 先把对象转成键值对数组,再批量生成重复元素后合并为一维数组
const outcomes = Object.entries(weights).flatMap(([result, count]) => Array(count).fill(result))

补充容错处理

如果你的权重值可能出现非正整数的异常情况,可以加一层判断过滤无效配置:

const outcomes = []
for (const result in weights) {
  const appearCount = weights[result]
  // 仅当次数为正整数时才生成元素
  if (Number.isInteger(appearCount) && appearCount > 0) {
    for (let i = 0; i < appearCount; i++) {
      outcomes.push(result)
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 14:27:03