簡體   English   中英

如何根據 JavaScript 中的 integer 值將 object 鍵多次推送到數組

[英]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);

但是,如果您願意,可以按照以下方式使用fillspread

 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM