Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/84.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 避免随机重复结果?_Jquery_Random - Fatal编程技术网

Jquery 避免随机重复结果?

Jquery 避免随机重复结果?,jquery,random,Jquery,Random,我试图在4个div内随机切换一些图像,但重复结果时遇到问题。 尽管每个例子都有 1,4,2,3 然后 4,1,3,2 我要走了 2,2,4,2然后是1,3,3,4 所以我需要找到一个避免重复数字的解决方案 这是密码 var tempo = setInterval(function() { $('.pub').each(function(i) { var imagens_pubs = ['img_1.jpg', 'img_2.jpg', 'img_3.jpg', 'img_

我试图在4个div内随机切换一些图像,但重复结果时遇到问题。 尽管每个例子都有

1,4,2,3 然后 4,1,3,2

我要走了

2,2,4,2然后是1,3,3,4

所以我需要找到一个避免重复数字的解决方案

这是密码

var tempo = setInterval(function() {
    $('.pub').each(function(i) {
        var imagens_pubs = ['img_1.jpg', 'img_2.jpg', 'img_3.jpg', 'img_4.jpg'];
        var rand = Math.floor(Math.random()*imagens_pubs.length);
        $(this).html('<a href="http://www.mysite.com" target="_blank"><img src="pubs/'+imagens_pubs[rand]+'" width="220px" height="50px"></img></a>');
    });
}, 5000);
var tempo=setInterval(函数(){
$('.pub')。每个(函数(i){
var imagens_pubs=['img_1.jpg'、'img_2.jpg'、'img_3.jpg'、'img_4.jpg'];
var rand=Math.floor(Math.random()*imagens_pubs.length);
$(this.html(“”);
});
}, 5000);

您应该了解如何生成数组的随机排列。该算法非常简单,易于实现:

To shuffle an array a of n elements (indices 0..n-1):
  for i from n − 1 downto 1 do
       j ← random integer with 0 ≤ j ≤ i
       exchange a[j] and a[i]

这是因为对于每个
.pub
,您都从同一数组中选择了一个随机项。最简单的方法是在选择元素后删除它,停止重复选择

var tempo = setInterval(function() {
    var imagens_pubs = ['img_1.jpg', 'img_2.jpg', 'img_3.jpg', 'img_4.jpg'];

    $('.pub').each(function() {
        var rand = imagens_pubs.splice(Math.floor(Math.random() * imagens_pubs.length), 1)[0]; // Chose a random element and remove it. See the documentation for Array.splice.

        $(this).html('<a href="http://www.mysite.com" target="_blank"><img src="pubs/' + rand + '" width="220px" height="50px"></img></a>');
    });
}, 5000);​
var tempo=setInterval(函数(){
var imagens_pubs=['img_1.jpg'、'img_2.jpg'、'img_3.jpg'、'img_4.jpg'];
$('.pub')。每个(函数(){
var rand=imagens_pubs.splice(Math.floor(Math.random()*imagens_pubs.length),1)[0];//选择一个随机元素并将其删除。请参阅Array.splice的文档。
$(this.html(“”);
});
}, 5000);​
注意,我们已将
imagens\u pub
的声明移出
each()
,否则将为each
.pub
重新声明数组

你可以看到它在这里工作