簡體   English   中英

數組中的隨機重復元素

[英]Random repeating elements in an array

我在 underscore.js 中使用_.sample從數組中提取隨機元素。

我在源列表中的元素少於我想要采樣的數量,但它的最大值為 4(源的長度)。

從數組中的 4 個選項返回 17 個隨機元素(顯然是重復的)還有哪些其他選項? 我看到很多關於刪除重復的內容,但無法弄清楚是什么讓他們重復。

let dots = _.sample([component 1, component 2, component 3, component 4], 17);

您只需要從 0 到 3 獲取隨機數(您可以使用下划線的_.random ),並將它們用作索引以從您的組件數組中獲取元素。

var components = [component1, component2, component3, component4]
var dots = []
for (var i = 0; i < 17; ++i) dots.push(components[_.random(3)]);

let dots = _.sample(Array.from({length: 5}).fill([component 1, component 2, component 3, component 4]).flat(), 17)

暫無
暫無

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

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