Sometimes you’ll need to have a loop in your code that loops around a number of times, but there’s no way of knowing in advance how many times you’ll want to loop. That’s when you’ll want to use a do/while loop: you want to do something, while some value is true. Script 3.9 writes out each row of numbers as always, but this time it checks first to see if a number has been used already before putting it in a cell. If it has, the script generates a new random number and repeats the process until it finds one that’s unique. Figure 3.6 shows the working, finally valid Bingo card.
window.onload = initAll; var usedNums = new Array(76); function initAll() { 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,0,0,0,0,1,1,1,1,1,2,2,2,2,3,3,3,3,3,4,4,4,4,4); var colBasis = colPlace[thisSquare] * 15; var newNum; do { newNum = colBasis + getNewNum() + 1; } while (usedNums[newNum]); usedNums[newNum] = true; document.getElementById(currSquare).innerHTML = newNum; } function getNewNum() { return Math.floor(Math.random() * 15); } |
To use a do/while loop:
✓ Tip
A common use for a do/while loop would be to strip blanks or invalid characters off data entered by a user. But again, remember that the do block of code always gets executed at least once, whether the while check evaluates to true or false.
13.59.140.238