Friday, 15 October 2010

JavaScript Array

In order to make my piracy myths appear randomly on the webpage I have used JavaScript to create a function. An array has been created containing all the myths then the floor() and random() methods of the Math object are used to pick one out at random. The code for this is demonstrated below -

function getMyth()
{
var piMyths = new Array();
piMyths[0] = "Pirates only want things for free.";
piMyths[1] = "Downloading music damages the artist.";
piMyths[2] = "No artists support piracy.";
piMyths[3] = "Piracy is stealing.";
piMyths[4] = "Piracy will kill creative arts.";
piMyths[5] = "Digital piracy costs the industy billions.";
piMyths[6] = "Piracy is illegal, and therefore wrong.";
piMyths[7] = "Pirates are all young people who don't really understand how society works.";
piMyths[8] = "Using pay services is so much easier.";
piMyths[9] = "It isn't expensive to just pay for stuff anyway.";
piMyths[10] = "You don't support the band by pirating their music.";
var randValue = Math.floor(Math.random() * piMyths.length);
document.write(piMyths[randValue]);
}
By using an array more information can be added quickly and easily by just editing this one piece of JavaScript. I have placed this script in an external .js document that can be linked to from any of my HTML pages. Then all I have to do is call upon the JavaScript function in the body of my HTML document in order to make the random quotes show up.

This can be see in action at http://jennoefur.comyr.com/piracy/arraydemo.html. Refreshing the page will bring up one of the randomly selected quotes.
  • Stumble This
  • Fav This With Technorati
  • Add To Del.icio.us
  • Digg This
  • Add To Facebook
  • Add To Yahoo

No comments:

 
Copyright 2010 Meow