重複なしで数値を生成することになっている新しい乱数ジェネレーターを試していますが、それを自分のページに適用しようとすると、多くの重複が生成されます。少なくとも60%の確率で、重複が1回、3回、2セットの重複がありました。
1から100までの一意の乱数を生成するからの答えを試していますが、20個に制限してもそのまま機能するようです。重複番号がゼロの状態で40回実行しました。それを既存の関数に入れようとすると、バラバラになります。私がここで何を見逃しているのか分かりますか?これは私の前の質問の続きですランダムな画像でテーブルを埋める
/* 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 + "'/>";
});
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加