2

Possible Duplicate:
Alternative to a million IF statements

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
  }
  else {
    // (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.

Community
  • 1
  • 1
newbie_coder
  • 41
  • 1
  • 3

2 Answers2

8

One possibility is to create a map:

var countries = {
    US: us,
    GR: gr
};

window.location = countries[country];

This works because you can get an object's property using strings. For example, if you have an object with a foo property:

var myObject = {};
myObject.foo = 4;

Then you can also get to foo this way:

var foosValue = myObject['foo'];

This is basically a very primitive hashmap, which is a common data structure in programming. This pattern is common in JavaScript.

Matt Greer
  • 60,826
  • 17
  • 123
  • 123
  • 5
    It's probably worth adding a default/fall-back to this: `window.location = countries[country] || genericpage;` just in case the user's in a location for which the country-map has no assigned value. – David Thomas Oct 14 '12 at 16:24
  • Got it!! I see that I need to use var/variables. Thank you for answering this newb question. – newbie_coder Oct 14 '12 at 17:06
1
var redirect = { "US": "http:this", "GR" : "http:that };

window.location = redirect[country] || alert("what are you trying to achieve?");
coolguy
  • 7,866
  • 9
  • 45
  • 71
Aki Suihkonen
  • 19,144
  • 1
  • 36
  • 57
  • +1 to Matt. Could there be a delay of +15 minutes on SO? I though I answered a question in 15 seconds. Not minutes. – Aki Suihkonen Oct 14 '12 at 16:38
  • Yes. Thanks. this works. I've started learning javascript last night so I don't quite understand "var" yet but at least I can figure out how to use it. – newbie_coder Oct 14 '12 at 17:09
  • 'var' declares a "local" variable. Without 'var' you are overwriting possibly a very important global variable used by your browser and/or extending the "search area" of the run time interpreter to find the label you are referring. That means performance penalty. – Aki Suihkonen Oct 14 '12 at 17:23