我正在尝试一个新的随机数生成器,它应该生成没有重复的数字,但是当我尝试将其应用到我的页面时,它会产生许多重复项。至少 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 + "'/>";
});
}
最佳答案
如果我理解正确,那么您需要: 1. 将 map
更改为 forEach
2. 您需要将保存已生成数字的数组移出forEach函数3.更改数字生成器循环
/* 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'));
// initialize the array
var arr = []
// map() the array; run a function on each loop...
cellArray.forEach(function (cel, idx) {
// generate numbers 1-40 and check if they were already generated
do {
var ran = Math.ceil(Math.random() * 40)
} while (arr.indexOf(ran) > -1);
//save the newly generated unique number
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 + "'/>";
});
}
关于Javascript独特的随机数生成器不生成唯一的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47391513/