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 readinstead, 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. We've gotten rid of the duplicate numbers, but some of the spaces are now blank. Time to go back to the drawing board.


Tips

  • 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.





JavaScript and Ajax for the Web(c) Visual QuickStart Guide
JavaScript and Ajax for the Web, Sixth Edition
ISBN: 0321430328
EAN: 2147483647
Year: 2006
Pages: 203

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net