Useful JavaScript Game Extensions: Array#rand

Ayn Rand

Ayn Rand

Part 3 of 256.

/**
 * Randomly select an element from the array. The array remains unmodified.
 *
 * @returns A random element from an array, or undefined if the array is empty.
 */
Array.prototype.rand = function() {
  return this[rand(this.length)];
};

Building on the last installment of a global rand method, we can easily extend Array to provide simple random element selection.

// Example:
["rock", "paper", "scissors"].rand()

Selecting options from a loot table, or random AI actions is now wonderfully easy. With all these extensions the theme is the same, start with the best interface for the programmer and extend what you must to make it happen.

Author: Daniel X

Heretic priest of the Machine God. I enjoy crawling around in Jeff Bezo's spaceship, bringing technology to the people, and long walks outside of time and space.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s