简体   繁体   English

数组中的随机重复元素

[英]Random repeating elements in an array

I'm using _.sample in underscore.js to pull random elements from an array.我在 underscore.js 中使用_.sample从数组中提取随机元素。

I have less elements in the source list than the amount I want to sample, but it's maxing out at 4 (the length of the source).我在源列表中的元素少于我想要采样的数量,但它的最大值为 4(源的长度)。

What are some other options for returning 17 random elements (with repeats, obviously) from 4 options in an array?从数组中的 4 个选项返回 17 个随机元素(显然是重复的)还有哪些其他选项? I'm seeing a lot on removing the repeats but can't figure out what allows for them to repeat.我看到很多关于删除重复的内容,但无法弄清楚是什么让他们重复。

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

You just need to get random numbers from 0 to 3 (you can use underscores's _.random ), and use them as index to get elements from you components array.您只需要从 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