Useful JavaScript Game Extensions: Array#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.

Leave a Reply

Your email address will not be published. Required fields are marked *