【发布时间】:2018-05-03 15:25:24
【问题描述】:
我正在尝试一个新的随机数生成器,它应该生成没有重复的数字,但是当我尝试将它应用到我的页面时,它会产生许多重复。至少有 60% 的时间存在重复,一次重复三次,两次重复。
我正在尝试来自 Generate unique random numbers between 1 and 100 的答案,即使我将其限制为 20 个数字,它似乎也能正常工作。以零重复数字运行 40 次。当我试图把它放在我现有的函数中时,它就会分崩离析。知道我在这里缺少什么吗?这是我之前的问题Fill table with random images的延续@
/* The part of what each image url has in common
⍟ var base = 'images/Image_'
*/
var base = 'images/Image_';
var suff = '.jpg';
function randomCellBG(base) {
// Reference the <table>
var T = document.getElementById('mainTable');
/* Collect all .cell into a NodeList and convert
|| it into an array
*/
var cellArray = Array.from(T.querySelectorAll('.cell'));
// map() the array; run a function on each loop...
cellArray.map(function(cel, idx) {
// Get a random number 1 - 9
var arr = []
while (arr.length < 9) {
var ran = Math.ceil(Math.random() * 40)
if (arr.indexOf(ran) > -1) continue;
arr[arr.length] = ran;
}
/* Concatenate base and random number to form
|| a string of a url of an image
⍟ result: "images/Image_08.jpg"
*/
var img = base + ran.toString() + suff;
/* Assign that url as the value to the
|| backgroundImage property of the .cell
|| in current iteration
*/
cel.innerHTML = "<img src='" + img + "'/>";
});
}
【问题讨论】:
-
您正在为
cellArray中的每个项目生成一组新的 5 个唯一随机数。这些集合之间可能存在重叠。旁注:如果您真正想做的是.forEach,请避免使用.map。它们有不同的用途。 -
抱歉,在用一组受限的数字测试了代码的执行情况后,忘记改回代码了。我想从一组 40 个中选择 9 个。
-
你应该在
cellArray.map之前生成随机数,而不是在里面
标签: javascript random duplicates