SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Member
    Join Date
    Dec 2012
    Posts
    12
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question Help create a function.

    My question is how to make a function of this condition:

    Code:
    for(i=0;i<30;i++)
    {
      if(i==0)
      {
        if(a[i].c<50) a[i].y--;
        else if(a[i].c>=50 && a[i].c<100) a[i].y++;
        else {a[i].c=0; a[i].y=65;}
        a[i]++;
      }
      //[...]
      else if(i==3)
      {
        if(a[i].c<50) a[i].y--;
        else if(a[i].c>=50 && a[i].c<100) a[i].y++;
        else {a[i].c=0; a[i].y=65;}
        a[i]++;
      }
       //[...]
    }
    I would like to shorten the code:
    Code:
    if(i==0) f(a[i].c,a[i].y);
    //[...]
    else if(i==3)  f(a[i].c,a[i].y);
    I'm trying this:
    Code:
    function f(i,Y)
    {
    if(i<50) Y--;
    else if(i>=50 && i<100) Y++;
    else {i=0; Y=65;}
    i++;
    }
    But it ds'not work.
    How to do it correctly?

  2. #2
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,785
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    You don't need a function to shorten that code as a switch statement cal shorten it without needing a function call:

    Code:
    for(i=0;i<30;i++)
    {
       switch(i) {
      case 1: case 3:
        if(a[i].c<50) a[i].y--;
        else if(a[i].c>=50 && a[i].c<100) a[i].y++;
        else {a[i].c=0; a[i].y=65;}
        a[i]++;
        break;
      //[...]
      default:
      //[...]
      }
    }
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •