Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Better way to write if/else statement? Maybe use array? [duplicate]

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.

like image 468
newbie_coder Avatar asked Jun 14 '26 05:06

newbie_coder


2 Answers

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.

like image 154
Matt Greer Avatar answered Jun 16 '26 17:06

Matt Greer


var redirect = { "US": "http:this", "GR" : "http:that };

window.location = redirect[country] || alert("what are you trying to achieve?");
like image 20
Aki Suihkonen Avatar answered Jun 16 '26 19:06

Aki Suihkonen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!