The JavaScript Diaries: Part 14/Page 3
[previous]
The JavaScript Diaries: Part 14 - The Math Object
Finding the Maximum or Minimum Value
Other Uses
We can use the random()
and floor()
methods to create a random quotes script. Place this in an external file with a link to it in the head
section of the page where you want the quotes displayed:
Then place this in the place on the page where you want the quotes to be displayed:
Basically, what we did here was to create an array and give it six elements. We then set a formula to create a "random number generator." First we declared the variable quote
, and gave it our formula. The "formula" goes like this: we used the floor()
method to return an integer; then we created a random number by using the random()
method and multiplying it by 6 (the number of elements in our array). The document.write
object then displays the random quote.
You can do the same thing for images. You can use the script above, changing the quotes to images, or use one like below:
Then, just place this where you want the image displayed on the page:
This one is a bit different than the previous one. It uses the getElementById()
method to replace the contents of the scr
attribute. This makes it very unobtrusive, meaning that the JavaScript is kept completely off the page and the HTML code is used to display the results. We'll see more of this when we study the Document Object Model (DOM).
Using the with
Statement
If you plan on using several statements with an object, you can use the with
statement as a shortcut. For instance, to calculate the area of a circle, you would use the following statement:
With this format, you need to write the Math object each time you want to call a property or method. Instead, you can use the with
statement:
Another example (with thanks to William Wen) that demonstrates it a little better is as follows. This script:
could be written as:
That should save some time when you have to reuse the same object over and over.
Conclusion
That wraps up our study of the Math
object. As you can see it can be quite useful in the proper circumstances. Be sure to check out the scripts over at JavaScript Source in the Math Related section for additional examples and usages. Also, remember that, if you create any new scripts that you think would be useful for others — math related or otherwise, be sure and submit them to the JavaScript Source site and I will post them, giving you credit and a link back to your Web site. (It's also a great way to create an online resume.)
A serious note for those of you who, like me, are not math wizards: The formulas for JavaScript calculations can be found in reference books and on the Internet. You can also ask for help on the JavaScript forum over at WebDeveloper.com.
In our next installment, we'll take a look at the Date
object and its different uses. Until then, keep on codin'!
Continue on to "The JavaScript Diaries: Part 15"
[previous]
URL: