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/
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);
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.