1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Please Help! JavaScript Problem :(

Discussion in 'JavaScript' started by UberSoftware, Aug 19, 2008.

  1. #1
    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):
     
    UberSoftware, Aug 19, 2008 IP
  2. jack_ss

    jack_ss Guest

    Messages:
    94
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    0
    #2
    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):
     
    jack_ss, Aug 19, 2008 IP
  3. UberSoftware

    UberSoftware Peon

    Messages:
    24
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks so much! That was a huge help! :D
     
    UberSoftware, Aug 19, 2008 IP
  4. Logic Ali

    Logic Ali Well-Known Member

    Messages:
    170
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    108
    #4
    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):
     
    Logic Ali, Aug 19, 2008 IP
  5. UberSoftware

    UberSoftware Peon

    Messages:
    24
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Thanks so much :)
     
    UberSoftware, Aug 20, 2008 IP