3 ms·
Sometimes I have to use a hack in javascript to create a quick switch, instead of if...else: if(n==0) dir="north" else if(n==1) dir="east" else if(n==2)
by TweedHeads 17y ago
Sometimes I have to use a hack in javascript to create a quick switch, instead of if...else:
if(n==0) dir="north"
else if(n==1) dir="east"
else if(n==2) dir="south"
else if(n==3) dir="west"
or switch:
switch(n){
case 0: dir="north"; break;
case 1: dir="east"; break;
case 2: dir="south"; break;
case 3: dir="west"; break;
}
I'll use:
dir=["north","east","south","west"][n]
I hope you find it useful in some cases too
- apu 17y agoThis is similar to the accepted idiom in python as well: create a dictionary mapping choices to outcomes. For the special case of sequential numerical choices, a list works as well. For the special-special case of numerical choices for single-word string outcomes, I often use: dir = 'north eash south west'.split()[n]