繁体   English   中英

在JavaScript中以概率使用div的随机数组

[英]Use a random array of div in JavaScript with probability

我尝试使用JavaScript编写脚本,在该脚本中尝试构建具有随机墙壁,门,窗户和装饰(以及随机地板)的建筑物

但是我尝试添加以下可能性:在楼下,门的概率更大,窗户的概率不为零;在楼上,门的概率更大,窗户的概率不为零,我得到了楼上和楼下的条件。

你能帮助我吗?

看一看我在代码片段中编写的pickItem函数。 在这种情况下,我已经设定,让你在两个参数,一个是传递一个数组items (即你的items阵列),而另一个是一个chance阵列,你可以自己创建。 chance阵列定义了您的items阵列中每个元素被拾取的机会。 看一下代码片段,看看如何基于我的letters数组创建chance

如果您观察到输出结果,则可以看到letters中的项目“ a”通常被选择1/2或大于1/2的时间,因为它有50%的机会

因此,如果将此逻辑应用于items数组,则可以使其比其他items更频繁地选择items中的特定元素。

 function rand(intMin, intMax) { return Math.floor(Math.random() * (intMax - intMin + 1) + intMin); } let letters = ['a', 'b', 'c', 'd', 'e', 'f']; // dummy data, this is your items array /* a --> 50% b --> 20% c --> 10% d --> 5% e --> 10% f --> 5% */ // The following chances can be defined in an array like so: // abcdef let chance = [50, 20, 10, 5, 10, 5]; // chance as a percentage (%) function pickItem(items, chance) { // Pick an item from the letters array as defined by the chance let randIndex = rand(0, items.length - 1); // pick a random letter index while (!(chance[randIndex] >= rand(1, 100))) { // If the chance of that letter being picked isnt met, then pick a new letter randIndex = rand(0, items.length - 1); // pick a new random letter index } return items[randIndex]; // return the letter when found } // To show the function working we can print a bunch of letters: for (var i = 0; i < letters.length * 2; i++) { // Print out a picked item 12 times console.log(pickItem(letters, chance)); // At least 6 of these items (1/2 the time) should be 'a' } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM