-1
<script type="text/javascript"> 
var a = new Array(
"Jane",
"Tom,", 
"Alan,",
"Mary");
</script>
<script type="text/javascript">
document.write(a[Math.floor(Math.random()*a.length)]);
</script>

ate an apple  

Is there away of reusing the answer to (a[Math.floor(Math.random()*a.length)]) later on in a script?

So for example I could later use text along the lines of Harry asked "answer" if they had enjoyed the apple

Mephy
  • 2,978
  • 3
  • 25
  • 31

2 Answers2

4

You can store the answer in a variable

var ans = a[Math.floor(Math.random()*a.length)]
Jake
  • 407
  • 4
  • 13
0

Another way to make this task

var a = new Array("Jane","Tom,", "Alan,","Mary");
// use a varible named "answer" for get the valu of "a" array value.
var answer =a[getRandomArbitrary(0,a.length)];

alert(answer);

// can use the "answer" variable anywhere like this.
alert("Harry asked "+answer+", if they had enjoyed the apple");

/*
function for get the integer value between two numbers.
*/
function getRandomArbitrary(min, max) {
    return parseInt(Math.random() * (max - min) + min);
}
Thilina Dharmasena
  • 2,243
  • 2
  • 19
  • 27