Matt Matt - 7 months ago 13
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

if.select (

category1 = 1
category2 = 2
category3 = 3

Answer

Use a dictionary (works similarly to enum):

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

JSFiddle

Here is a switch case example:

switch(id){
  case 'category1':
    i = 1;
    break;
  case 'category2':
    i = 2;
    break;
  case 'category3':
    i = 3;
    break;
}

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.