随机生成的数字 - "检查"功能

时间:2014-03-30 21:21:41

标签: javascript if-statement for-loop random

我有一个3x4的图像表,当页面加载所有单独的图像时,为了制作一个图像" (图像是碎片,以创造一些拼图)。我有一个名为automate的按钮,当点击时会随机化图像。我需要的是一个功能,以便检查"看看是否已经使用了一个数字(希望代码有助于理解这一点)。

JS随机化图像:

function auto(){
    for (i = 0; i <= 12; i++){ 
    r=Math.floor(Math.random()*12);
    alert(r)   // Just shows where I'm at for figuring it out
    document.images[i].src="pic"+r+".gif"
}

我的图像被称为&#34; pic0,pic1&#34;因此,随机数0-12将随机化图像源。

我现在需要的是一个功能,它将逐步浏览图像0-11并检查是否已经使用了一个数字以避免重复图像。这是我到目前为止的功能,但现在卡住了。

JS for Check:

for (i=0; i < 12; i++){
check[i]=0;
}

if ( check[r] === 0)
{
    document.images[i].src = "pic" + r + ".gif";
    check[r] = 1;
}
else {
    while (check[r] ===0){
        r= (r+1) % 12;
        document.images[i].src = "pic" + r + ".gif";
        check[r] = 1;
    }

2 个答案:

答案 0 :(得分:2)

你想要的是一个争夺功能。

scramble = function(x) {
   var y = [];
   while(x.length > 0) y.push(x.splice(Math.floor(Math.random() * x.length), 1)[0]);
   return y;
}
scramble([1,2,3,4,5,6])
// [2, 4, 3, 5, 1, 6]

在上面的代码中,我们继续从x中选择一个随机索引,然后将其删除并将其附加到数组y。这样,x最终将为空,y将成为x的加扰版本。

答案 1 :(得分:1)

您无需检查该号码是否已被使用。相反,用数字1 - n填充一个数组并将它们洗牌:

// using the suffle function here:
// http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array

var imgIndices = [];
for ( i=0; i < 12; i++ )
    imgIndices.push( i );
imgIndices = shuffle( imgIndices );

for ( var imgNum=0; imgNum < imgIndices.length; imgNum++ )
    picName="pic"+imgIndices[ imgNum ]+".gif"
相关问题