...

View Full Version : Possible to use Math.random with multiple arrays to display random sentence



xyhuang
05-25-2005, 04:55 AM
Is it possible to put multiple arrays in math.random/math.floor to display a random sentence in a text box like this?

<html>
<head>
<title>Sample Page</title>
<script type="text/javascript">
subject=new array();
subject[0]="You"
subject[1]="Your friend"
subject[2]="Bill Gates"
subject[3]="Michael Jackson"

predicate=new array();
predicate[0]="should"
predicate[1]="will"
predicate[2]="was"
predicate[3]="could"

ending=new array();
ending[0]="be rich!"
ending[1]="be dead!"
ending[2]="be useless!"
ending[3]="be a victim to internet scams!"

function randomsentence()
{
random_sentece=subject[Math.floor(Math.random()*subject.length)],predicate[Math.floor(Math.random()*predicate.length)],ending[Math.floor(Math.random()*ending.length]
document.scriptform.scriptinput.value=random_sentence
}
</script>
</head>
<body>
<form>
<input name="scriptinput" /><input type="button" value="Random Sentence" onClick="randomsentence() />
</body>


Oh yeah! Some of this javascript(a little bit) is copied from http://www.javascriptkit.com/script/script2/punchline.shtml

Philip M
05-25-2005, 08:53 AM
<script type="text/javascript">
subject=new Array();
subject[0]="You "
subject[1]="Your friend "
subject[2]="Bill Gates "
subject[3]="Michael Jackson "

predicate=new Array();
predicate[0]="should "
predicate[1]="will "
predicate[2]="was "
predicate[3]="could "

ending=new Array();
ending[0]="be rich! "
ending[1]="be dead! "
ending[2]="be useless! "
ending[3]="be a victim to internet scams! "

function randomsentence()
{
var part1 = subject[Math.floor(Math.random()*subject.length)];
var part2 = predicate[Math.floor(Math.random()*predicate.length)];
var part3 = ending[Math.floor(Math.random()*ending.length)];
var random_sentence= part1 + part2 + part3
document.forms[0].scriptinput.value=random_sentence
}
</script>
<form>
<input name="scriptinput" /><input type="button" value="Random Sentence" onClick="randomsentence()" />
</body>

This gives results such as "Bill Gates was be useless".

You had a good many typos, and remember that JavaScript is case sensitive. Array, not array.

xyhuang
05-26-2005, 03:48 AM
Thanks! I'm new at JavaScript,so I don't know much about what is capitalized and what isn't.Thanks for pointing out the grammar mistakes,too!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum