[英]How to push object keys to an array multiple times based on their integer values in JavaScript
在发布此问题时,我已经查看了几个网站,包括通过建议的答案,所以请原谅我是否在其他地方得到了回答。 我对 JavaScript(和一般编码)非常陌生。 我正在做一个“加权彩票”项目,我心里有一个方法,我相信它会起作用,但我被困在一个特定的点上。
我有一个 object,它包含作为 object 键的结果,以及作为 integer 类型的 object 值生成特定结果的次数。 具体来说,这个:
const weights = {
'win': 5,
'loss': 10,
'tie': 3
}
我想根据它们的关联值将 object 键多次推送到一个名为“结果”的数组。 对于上面的示例,它会生成一个数组,其中列出了 5 次“赢”、10 次“输”和 3 次“平局”。
我遇到过 .fill 方法,但在这种情况下它似乎不起作用,我希望 object 项目的数量是动态的(它们的数量和它们的值 - 即有 15 个不同的 '每个结果都分配有不同的值)。
任何指针? 感谢大家提供这么好的资源!
fill
可以用于此,但我想我只是使用循环:
const outcomes = [];
for (const [key, count] of Object.entries(weights)) {
for (let n = count; n > 0; --n) {
outcomes.push(key);
}
}
现场示例:
const weights = { "win": 5, "loss": 10, "tie": 3 }; const outcomes = []; for (const [key, count] of Object.entries(weights)) { for (let n = count; n > 0; --n) { outcomes.push(key); } } console.log(outcomes);
但是,如果您愿意,可以按照以下方式使用fill
和spread :
const outcomes = []; for (const [key, count] of Object.entries(weights)) { outcomes.push(...Array.from({length: count}).fill(key)); }
现场示例:
const weights = { "win": 5, "loss": 10, "tie": 3 }; const outcomes = []; for (const [key, count] of Object.entries(weights)) { outcomes.push(...Array.from({length: count}).fill(key)); } console.log(outcomes);
David 的回答指出了一种比这更好的fill
方法(我忘记了start
和end
,doh,):但我会稍微不同地做:
const outcomes = []; for (const [key, count] of Object.entries(weights)) { const start = outcomes.length; outcomes.length += count; outcomes.fill(key, start, outcomes.length); }
现场示例:
const weights = { "win": 5, "loss": 10, "tie": 3 }; const outcomes = []; for (const [key, count] of Object.entries(weights)) { const start = outcomes.length; outcomes.length += count; outcomes.fill(key, start, outcomes.length); } console.log(outcomes);
也就是说,David 的回答的优点是您预先告诉 JavaScript 引擎数组将有多少元素,可用于优化。 它通常无关紧要,在这里可能无关紧要,但它仍然存在。
你可以用填充来做到这一点。 您可以创建一个新的数组,将合并的权重作为长度参数,然后像这样填充它。
const weights = { 'win': 5, 'loss': 10, 'tie': 3 }; let outcomes = new Array(Object.values(weights).reduce((value, initial) => value+initial)); let pos = 0; for(let [key, value] of Object.entries(weights)) { outcomes.fill(key, pos, pos += value); } console.log(outcomes);
也许这会有所帮助:
const weights = {
win: 5,
loss: 10,
tie: 3
}
const result = []
Object.keys(weights).forEach(name => {
const times = weights[name]
result.push(...new Array(times).fill(name))
})
console.log(res)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.