Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > PHP/MySQL/Scripting

Language Essentials

  • Print
  • + Share This
This chapter is from the book

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.

window.onload = newCard;
var usedNums = new Array(76);

function newCard() {
     if (document.getElementById) {
        for (var i=0; i<24; i++) {
           setSquare(i);
        }
     }
     else {
        alert("Sorry, your browser doesn't support this script");
     }
}

function setSquare(thisSquare) {
     var currSquare = "square" + thisSquare;
     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);
     var colBasis = colPlace[thisSquare] * 15;
     var newNum = colBasis + getNewNum() + 1;

     if (!usedNums[newNum]) {
         usedNums[newNum] = true;
        document.getElementById(currSquare). innerHTML = newNum;
     }
}

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

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.

  • + Share This
  • 🔖 Save To Your Account