In this chapter we looked at how JavaScript can make decisions based on conditions. We also looked at loops and functions.
Using document.write(), write code that displays the results of the 12 times table. Its output should be the results of the calculations. 12 * 1 = 12 12 * 2 = 24 12 * 3 = 36 ..... 12 * 11 = 132 12 * 12 = 144 |
||
A: |
<html> <body> <script language=JavaScript> var timesTable = 12; var timesBy; for (timesBy = 1; timesBy < 13; timesBy++) { document.write(timesTable + " * " + timesBy + " = " + timesBy * timesTable + "<br>"); } </script> </body> </html> We use a for loop to calculate from 1 * 12 up to 12 * 12. The results are written to the page with document.write(). What's important to note here is the effect of the order of precedence; the concatenation operator (the +) has a lower order of precedence than the multiplication operator, *. This means that the timesBy * timesTable is done before the concatenation, which is the result we want. If this were not the case, we'd have to put the calculation in parentheses to raise its order of precedence. |