Matt Matt - 2 years ago 87
Javascript Question

If Then Select From List

In JavaScript, is there a way to select if then from a list. I remember doing it in Visual Basic.

So instead of

if (id == "category1") {i = 1};
if (id == "category2") {i = 2};
if (id == "category3") {i = 3};

Is there something like (

category1 = 1
category2 = 2
category3 = 3

Answer Source

Use a dictionary (works similarly to enum):

var dictionary = {"category1": 1, "category2": 2, "category3": 3}; 
i = dictionary[id]


Here is a switch case example:

  case 'category1':
    i = 1;
  case 'category2':
    i = 2;
  case 'category3':
    i = 3;

I prefer the dictionary approach over the switch-case approach because it's a bit less code to write every time you add a new category.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download