2014-10-01 66 views
-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 

稍后在脚本中是否有重复使用(a[Math.floor(Math.random()*a.length)])的答案?如何重用随机结果?

因此,举例来说,我可以在以后使用文本一起的Harry asked "answer" if they had enjoyed the apple

回答

4

线可以将答案存储在变量

var ans = a[Math.floor(Math.random()*a.length)] 
0

另一种方法,使这项任务

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); 
 
}