Thursday, April 21, 2011

JavaScript Random Message

One thing great about JavaScript is that it can be easy to write code for. Unlike programming languages, scripting languages are designed to have less code due to download speeds. Instead of vectors and lists, JavaScript uses arrays for all lists, even when you need to add more indexes to the array:

var messages;
// create array
messages = new Array("Hello World!", "This is a test.", "Look Eddy! It moves and swears!", "Robert Kotick likes men.", "That is all.");

// OR

var num = 0;
messages[num++] = "Hello World!";
messages[num++] = "This is a test.";
messages[num++] = "Look Eddy! It moves and swears!";
messages[num++] = "Robert Kotick likes men.";
messages[num++] = "That is all.";

// get random element
var ele = messages[Math.floor(Math.random() * messages.length)];

Simply create the array and use the ele variable to grab a random value from said array. This could be useful for JavaScript games you might work on in the future and for a random message for a website, like at GoNintendo (except those messages are displayed using a server-side scripting language like PHP as opposed to a client-side scripting language like JavaScript).

This would take more source code in C++. However, C++ gives you more control over everything, and JavaScript, in this programmer's opinion, is a bit of a mess at times. Still, it's a good language to learn for beginners.

Also, pingas. That is all.

No comments:

Post a Comment