Reputation: 21
I'm using Javascript to generate random movie plots from several arrays of word lists using the Math.random function which I've adapted from another generator. The code generates a random name for the main character from an array of names, and I need to repeat this same name in other parts of the plot, e.g. if the name Fred is chosen at the start then I need to say Fred in a few other sentences. If I just use the same Math.random function for subsequent instances of the name, I sometimes get a new random name from the list instead. Is there a way to "remember" the random name chosen at the start and display it whenever I want? Code sample:
<html>
<input type="button" value="Generate" onclick="GetPlot()">
<textarea name="plot" id ="plot" cols="100" rows="25"></textarea>
<script type="text/javascript">
function GetPlot(){
var Name = new Array("Fred", "John", "Roger");
var n = "";
n = n + Name[Math.round(Math.random()*(Name.length-1))];
n = n + " is the lead character." + Name[Math.round(Math.random()*(Name.length-1))] + " is wanted by the FBI.";
document.getElementById('plot').value = n;
}
</script>
</html>
Upvotes: 2
Views: 1273
Reputation: 9808
Math.random()
can generate a different number everytime you use it. you can just save the random number generated once and use it again. And anyways you are storing name in n
once, you can use that again while making the sentence.
<html>
<input type="button" value="Generate" onclick="GetPlot()">
<textarea name="plot" id ="plot" cols="100" rows="25"></textarea>
<script type="text/javascript">
function GetPlot(){
var Name = new Array("Fred", "John", "Roger");
var randomIndex = Math.round(Math.random()*(Name.length-1));
var n = "";
n = n + Name[randomIndex];
n = n + " is the lead character." + n + " is wanted by the FBI.";
document.getElementById('plot').value = n;
}
</script>
</html>
Upvotes: 1