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