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



我看了好几个网站,包括在发布这个问题时的建议答案,所以如果在其他地方有答案,请原谅我。我对JavaScript(和一般的编码)非常陌生。我正在做一个"加权彩票"项目,我脑子里有一个方法,我肯定会起作用,但我在一个特定的点上卡住了。

我有一个对象,其中包含作为对象键的结果和作为整型对象值的特定结果产生的次数。具体来说,这样的:

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

我想把对象键数组称为"结果"多次根据他们的相关值。在上面的例子中,它会生成一个数组,其中'win' 5次,'loss' 10次,'tie' 3次。

我遇到了。fill方法,但它似乎不能在这样的情况下工作,我希望对象项目的数量是动态的(无论是在它们的数量和它们的值-即有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以及传播如果你想:

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(我忘记了startend, 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)

最新更新