0

Still working on JavaScript fundamentals. The following code prints out the correct images and attributes, but I want to randomise the images and I'm not sure how to do this. I found other articles about using the Fisher-Yates shuffle, but I can't seem to be able to implement it, and I'm not sure if it's the right decision.

var counter = 0;
var pictures = new Array();

    pictures[counter++] = ['http://example.com','img/pic1.jpg','Pic Logo'];
    pictures[counter++] = ['http://example2.com/','img/pic2.jpg','Pic 2 Logo'];
    pictures[counter++] = ['http://example3.com/','img/pic3.jpg','Pic 3 Logo'];

    function showImages() {
        var i = 0;
        for (var p = pictures.length-1; p >= 0; p--) {
            document.write('<div class="images"><a href="' + pictures[p][0] + '"><img src="' + pictures[p][1] + '" alt="' + pictures[p][2] + '" title="' + pictures[p][2] + '"  /></a></div>');
            i++;
        }
    }

Edit: How can I access specific items in my pictures array, similar to my original code? - http://jsfiddle.net/chris_s/eW9Tm/

4

1 回答 1

1

您可以使用 Jonas Silva 的shuffle函数来随机化数组:

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/array/shuffle [v1.0]
function shuffle(o){ //v1.0
    for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
};

你这样称呼它:shuffle(pictures);.

于 2013-02-11T18:13:46.843 回答