I been working on a educational game for my school and I'm stuck with this: It displays all the functions except just one random one. Can anyone help me fix this or give me a new more efficient code? var whichEvent=get_random(); var event=new Array(4) event[0]=Robbery(); event[1]=Hurricane(); event[2]=Tornado(); event[3]=Reward(); event[whichEvent]; Code (markup): function get_random() { var ranNum= Math.floor(Math.random()*4); return ranNum; } Code (markup):
When you are creating your array, you run every single "event" function. Try this: function get_random() { var ranNum= Math.floor(Math.random()*4); if (ranNum == 0) Robbery(); if (ranNum == 1) Hurricane(); if (ranNum == 2) Tornado(); if (ranNum == 3) Reward(); } Code (markup):
Avoid calling anything event, since I.E. uses window.event. <script type='text/javascript'> function Robbery(){alert('Robbery')} function Hurricane(){alert('Hurricane')} function Tornado(){alert('Tornado')} function Reward(){alert('Reward')} var eventArray=[Robbery,Hurricane,Tornado,Reward]; function get_random(funcTable) { funcTable[ Math.floor( Math.random()*funcTable.length ) ](); } get_random(eventArray); </script> Code (markup):