A common task for JavaScript is to do something clever, like display a random image . Those of us old enough to remember the late 90s might recall an era when that was the coolest trick you could build into a web page.

Marcus found this approach to this problem, which is the sort of code that seems just plain ugly at first glance. At second glance, you can’t help but wonder- what were they thinking?


function random_imglink(){
 var myimages=new Array()
 //specify random images below. You can have as many as you wish
 myimages[1]="/files/design/FRT999Q.jpg"
 myimages[2]="/files/design/FRT978Q.jpg"
 myimages[3]="/files/design/FRT986Q.jpg"
 myimages[4]="/files/design/FRT908Q.jpg"
 myimages[5]="/files/design/FRT901Q.jpg"

 var ry=Math.floor(Math.random()*myimages.length)

 if (ry==0)
    ry=1
    document.write('<img src="'+myimages[ry]+'" border=0>')
}

 random_imglink()

 Notice how they avoid using a zero-indexed array. Then, when their randomizer returns a zero, they simply change it to one. This might look like a misuse of JavaScript’s arrays, or a misunderstanding of how best to shift a range of values, but it’s really a very clever way to weight the results to display FRT999Q.jpg 1/3 of the time, which is obviously the best image.

[Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!