HTML and CSS Reference
In-Depth Information
Returning a Random Array Item
In some programs, such as gaming apps, you might want to return a random value from
an array. You can use the array index numbers along with the Math.random() and
Math.floor methods to achieve this. Assuming that an array is not sparse, the total
number of array items is provided by the length property. To return a random index
from the array, you'd use the expression
Math.floor(Math.random()* array .length);
where array is the name of the array. The value returned by this expression would be
a random integer from 0 up to the value length - 1 , which corresponds to all of the
array indices. You could place this expression in a function such as
function randItem(arr) {
return arr[Math.floor(Math.random()*arr.length)];
using the arr parameter as the array to be evaluated. Then, to pick a random item from
any array, you could apply the randItem() function to any array as follows
var color = [“red”, “blue”, “green”, “yellow”];
var randColor = randItem(color);
and the randColor variable would contain one of the four colors chosen at random from
the color array.
Array Methods with ECMAScript 5
Program loops are often used with arrays, and starting with ECMAScript 5—the version
of JavaScript developed for HTML5—several new methods were introduced to allow
programmers to loop through the contents of an array without having to create a program
loop structure. Because these methods are built into the JavaScript language, they are
faster than program loops; however, older browsers do not support them, so you should
apply them with caution.
Each of these methods is based on calling a function that will be applied to the array
and its contents. The general syntax is
array . method ( function )
where array is the array, method is one of the methods supported in ECMAScript 5, and
function is the name of the function that will be applied to the array.
The function being called can have up to three parameters. The first parameter repre-
sents each array item's value. The second parameter represents each item's index number.
Finally, the third parameter represents the name of the array itself. Only the parameter
representing each item's value is required.
Function parameters can
be given any descriptive
name you choose, but
must be listed in the order
item value , item index ,
array name .
Running a Function for Each Array Item
The first method you'll explore, forEach() , is used to loop through the contents of an
array, running a function for each item in the array. The general syntax is as follows:
array .forEach( function )
Search WWH ::

Custom Search