2012-02-23 127 views
0

我試圖在4格內隨機切換一些圖片,但我遇到了重複結果的麻煩。 儘管每例如具有避免重複的結果?

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); 

回答

1

這是因爲每個.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);​ 

注意我們移動的imagens_pub申報了each()的,否則陣列將重新公佈各.pub

你可以在這裏看到這個工作; http://jsfiddle.net/3xcKb/

+0

您比較快! – 2012-02-23 11:25:36

+0

感謝您的幫助! – Pluda 2012-02-23 11:41:07

1

你應該看看如何生成一個數組的隨機排列。該Knuth shuffle算法非常簡單,易於實現:

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]