Random post

Our simple little blog manager is boring. We want to enjoy the thrill of reading a random post, and we can do it easily using a couple of mathematical methods made available to our JavaScript code by the Math class.

We are going to use Math.random(), that gives us a pseudo-random number in (0,1), and Math.floor() that truncates a number to the lower integer.

We add a button to the HTML code and make it call, as onclick reaction, this function:

function randomPost() {
var i = Math.floor(Math.random() * blog.length);
var element = resetBlog();
showPost(element, i, false);

Math.random() generates a number in (0,1), we multiply it for the number of items in the blog, and then we reduce it to an integer in [0, blog.length - 1] through Math.floor().

More information on the JavaScript Object Oriented features in chapter nine of Head First JavaScript. The code here is heavily based on an example you can find in this fun and useful book.

No comments:

Post a Comment