JavaScript Language Essentials | Page 4 | WebReference

JavaScript Language Essentials | Page 4

[previous] [next]

JavaScript Language Essentials

Working with Arrays

In this example, we're introducing another useful JavaScript object, the array. An array is a kind of variable that can store a group of information. Like variables, arrays can contain any sort of data: text strings, numbers, other JavaScript objects, whatever. You declare an array with the elements of the array inside parentheses, separated by commas, like so:

After this, the newCars array contains the three text strings with the car makes. To access the contents of the array, you use the variable name with the index number of the array member you want to use, in square brackets. So newCars[2] returns "Nissan", because array numbering, like most other numbering in JavaScript, begins at zero.

In this example, shown in Script 3.6, we begin making sure the Bingo card is valid. On a real Bingo card, each column has a different range of numbers: B is 1–15, I is 16–30, N is 31–45, G is 46–60, and O is 61–75. If you look back at Figure 3.1, you'll see that it is not a valid card, because it was generated with a version of the script that simply put a random number between 1 and 75 in each square. This example fixes that, with only two lines of changed or new code. When we're done, the card will look something like Figure 3.4. It's still not a valid Bingo card (note how there are duplicate numbers in some of the columns), but we're getting there.

Script 3.6. This script limits the range of values that can go into each column.

Figure 3.4
Figure 3.4 This Bingo card is improved, but not quite right yet, because there are duplicate numbers in some of the columns.

To use an array:

  1. var colPlace = new Array(0,1,2,3,4, 0,1,2,3,4,0,1,3,4,0,1,2,3,4,0,1, 2,3,4);

    We're concerned with limiting which random numbers go into which columns. The simplest way to keep track of this is to give each column a number (B: 0, I: 1, N: 2, G: 3, O: 4) and then calculate the numbers that can go into each column as (the column number x 15) + (a random number from 1–15).

    However, HTML tables are laid out in row cell order, not column cell order; that is, we're going across the first row, then across the second row, and so on, versus down the first column, then down the second column, and so on. The colPlace array keeps track of, for each square, which column it ends up in. It's the numbers 0–4 repeated five times (minus the free space; notice the sequence in the middle of the array 0,1,3,4 which skips the free space, which would be at position 2).

  2. var newNum = (colPlace[thisSquare] * 15) + Math.floor(Math.random() * 15) + 1;
    The newNum variable still generates the random numbers, but instead of coming up with a number from 1–75, it now calculates a random number from 1–15, and then adds that to the column number, colPlace[thisSquare], multiplied by 15—so, if our random number is 7, it would be 7 in the B column, 22 in the I column, 37 in the N column, 52 in the G column, and 67 in the O column.

Working with Functions That Return Values

Up to this point, all the functions that you've seen simply do something and then return. Sometimes, though, you want to return a result of some kind. Script 3.7 makes the overall script more understandable by breaking out some of the calculations in previous examples into a function which returns the random numbers for the cells on the Bingo card. Another function then uses this result.

Script 3.7. A function can return a value, which can then be checked.

To return a value from a function:

  1. var colBasis = colPlace[thisSquare] * 15;
    var newNum = colBasis + getNewNum() + 1;

    The first line is just a little bit of cleanup, in that we've calculated it in the last task; now, we're instead assigning it to a variable that we'll use in the second line.

    The second line is again just setting the newNum variable to our desired number, but here we've moved that random number generator into a function, called getNewNum(). By breaking the calculation up, it makes it easier to understand what's going on in the script.

  2. function getNewNum() {
       return Math.floor(Math.random() * 15);

    This code calculates a random number between 0 and 14 and returns it. This function can be used anywhere a variable or a number can be used.


  • Any value can be returned. Strings, Booleans, and numbers work just fine.

Updating Arrays

As you saw in Figure 3.4, the Bingo card script doesn't yet have a way to make sure that duplicate numbers don't appears in a given column. This example fixes that problem, while simultaneously demonstrating that arrays don't have to be just initialized and then read—instead, they can be declared and then set on the fly. This gives you a great deal of flexibility, since you can use calculations or functions to change the values in the array while the script is running. Script 3.8 shows you how, with only a few new lines of code.

Script 3.8. Changing the contents of arrays during the script is a very powerful technique.

To update an array on the fly:

  1. var usedNums = new Array(76);
    Here is a new way of declaring an array. We're putting into the usedNums variable a new array with 76 objects. As mentioned before, those objects can be anything. In this case, they're going to be Booleans, that is, true/false values.

  2. if (!usedNums[newNum]) {
       usedNums[newNum] = true;

    If the newNum slot in the usedNum array is false (represented by the ! before the statement, meaning "not"), then we set it to true and write it out to the card. If it's true, we don't do anything at all, leaving us with no duplicates, but possibly blank spaces on our card (Figure 3.5). That's not good either, which leads us to the next task.

    Figure 3.5

    Figure 3.5 We've gotten rid of the duplicate numbers, but some of the spaces are now blank. Time to go back to the drawing board.


  • Why is the array defined as containing 76 items? Because we want to use the values 1 to 75. If we initialized it to contain 75 items, the numbering would go from 0 to 74. 76 lets us use 1 through 75, and we'll just ignore item 0.
  • If you don't do anything to initialize Booleans, they'll automatically be false.

[previous] [next]