I’m developing a webpage but I need a JS script which selects a random page from a directory. At the moment I have this script;
<!-- Hide this script from old browsers --
var links = new Array(10)
links[0] = "anal.html"
links[1] = "brr-fail.htm"
links[2] = "anal.html"
links[3] = "brr-fail.htm"
links[4] = "anal.html"
links[5] = "brr-fail.htm"
links[6] = "anal.html"
links[7] = "brr-fail.htm"
links[8] = "anal.html"
links[9] = "brr-fail.htm"
links[10] = "anal.html"
function go() {
var a = 1+Math.round(Math.random()*10)
var i = a
location = links[i]
}
// -- End Hiding Here -->
</script>
(Don’t worry, it isn’t gay porn – meme)
As you can see, it is kinda complicated, and sometimes it brings up an “undefined” page error. Is there any way to make it select a random page from the whole directory? Say something like;
http://www.urlhere.co.uk/memes/random/
Thanks guys
Math random produces a value between
0and1, if you multiply with 10, you get number from0.0to9.9, and if you round that, you get number from0to10. So you don’t need to add 1 to it, that would result in 11 in some cases, wich you don’t have, since theundefined. Simply use:Edit: corrected my wrong 1st answer
Note: actually would not result a standard distribution of random numbers, since 0 and 10 would only result if,
Math.random()is 0.0 – 0.049… (0) and 0.95 – 0.99… (10) You can even the odds by this:This way a whole decimal range (x.0-x.9) floored down.