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/

1

1 Answer 1

1

You can use Jonas Silva's shuffle function to randomize arrays:

//+ 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;
};

You call it like this: shuffle(pictures);.

Sign up to request clarification or add additional context in comments.

1 Comment

I think I understand this, but how do I get it return the html and specific index items like I have in my original code? This actually prints to the console, but I'm not sure how to write it to the DOM jsfiddle.net/chris_s/EDTjZ

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.