www.webdeveloper.com
Results 1 to 4 of 4

Thread: A better /elegant way to write if/ else? Maybe use array?

  1. #1
    Join Date
    Oct 2012
    Posts
    4

    Red face A better /elegant way to write if/ else? Maybe use array?

    I am new to programming so I know very little. (Sorry for posting a newbie question)

    Here is my question.

    I have used "if, else" statement to redirect users depending on their country like this.

    if (country == 'US') {

    window.location=us

    else

    {

    if (country == 'GR') {

    window.location=gr

    .
    .
    .
    (repeated this for 5 times/5 different countries)

    Well, now, I need to redirect visitors to their states (i.e., California, Arizona, etc.).

    The problem is, if I keep using if/else statement, I know I have to repeat this for 50 times and the javascript code will end up looking ridiculous.

    I know there is a better way to do this.

    Can anyone show how to replace multiple if/else statement into an array? Array should be used in a situation like this? Am I correct?

    If I am wrong, can you please correct me & show me what other statement should be used instead?

    Thank you & once again, I apologize for putting up such a newbie question.

  2. #2
    Join Date
    Jan 2011
    Posts
    117
    window.location=country

  3. #3
    Join Date
    Nov 2010
    Posts
    1,053
    or maybe from the looks of it
    window.location=country.toLowerCase()

  4. #4
    Join Date
    Nov 2010
    Posts
    1,053
    but to go one level deeper on the if/else scenario you would probably want to put your information into an object and use it as a look up table:

    Code:
    <script type="text/javascript">
    var country="us";
    var state="Arizona"
    
    var countries={
    us:{Arizona:"az",California:"ca"},
    australia:{Victoria:"vic",nsw:"NSW"}
    }
    
    alert(countries[country][state])
    </script>

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

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



Recent Articles