简体   繁体   English

使用jquery分发数组元素随机列出

[英]Use jquery to distribute array elements to list randomly

I have a simulator here that's working just fine, this simulator have 48 blocks (DIV elements), i'm using Math.floor((Math.random() * 48) + 1) to randomly attach the results on each block.我这里有一个运行良好的模拟器,这个模拟器有 48 个块(DIV 元素),我使用Math.floor((Math.random() * 48) + 1)将结果随机附加到每个块上。 The problem is that they're too close on the final simulation (see image below):问题是它们在最终模拟中太接近了(见下图):

在此处输入图片说明

Is there a jquery / javascript function where i can return the array items from the simulation odd/even?是否有 jquery/javascript 函数,我可以从模拟奇数/偶数中返回数组项? Like, it will add each block like: 1,3,5,7,9 then 2,4,6,8 .就像,它会添加每个块,如: 1,3,5,7,9然后2,4,6,8

My code looks like this right now:我的代码现在看起来像这样:

if(adicionados.length < 48)
            {
                while(i<=eE && adicionados.length < 48)
                {
                    sol = Math.floor((Math.random() * 48) + 1);
                    if(adicionados.length == 0 || adicionados.indexOf(sol) == -1)
                    {                       
                        adicionados.push(sol);
                        //console.log(adicionados);
                        $("#base"+sol).attr("src", foto);
                        $("#base"+sol).attr("data-i", $(this).parent().parent().find('.relacionados-img').attr('data-cor')); 

                        i++;
                    }
                }

Thanks!谢谢!

You can use just two for loop because you have fixed row and col number and you are trying to draw a fixed pattern.您可以只使用两个 for 循环,因为您有固定的行号和列号,并且您正在尝试绘制固定模式。

for(var i=1;i<=8;i++)
{
    for(var j=1;j<=6;j++)
    {
        var sol=(i*6)+j;//if you are naming the boxes from left to right.
        if(i%2==1)
        {
            if(j%2==1)
            {
             //your code to draw those boxes.
            }
        }
        else
        {
            if(j%==0)
            {
                //your code to draw those boxes.
            }
        }
    }
}

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

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