Shortening javascript switch


I have a piece of code like this:

switch(v[0]){
    case 1:
        $(o).test({default:true}).on("click", function(e){
            stopf(e);
            func1(v[1]);}           
        });
        break;
    case 2:
        $(o).test({default:true}).on("click",function(e){
            stopf(e);
            func2(v[1]);}           
        });
        break;
    case 3:
        $(o).test({default:true}).on("click",function(e){
            stopf(e);
            func3();}       
        });
        break;
    case 4:
        $(o).test({default:true}).on("click",function(e){
            stopf(e);
            func4();}       
        });
        break;
    case 5:
        $(o).test({default:true}).on("click",function(e){
            stopf(e);
            func5(v[1],v[2]);}          
        });
        break;

    // AND ON AND ON....
}

As you can see the only difference is the funcX() part at the end of each line. Is there any way to shorten this code? Maybe something like this (tried it, doesn't work):

switch(v[0]){
    case 1: myfunc=func1(v[1]);break;
    case 2: myfunc=func2(v[1]);break;
    case 3: myfunc=func3();break;
    case 4: myfunc=func4();break;
    case 5: myfunc=func5(v[1],v[2]);break;
}
$(o).test({default:true}).on("click",function(e){
    stopf(e);
    myfunc);
}

If functions set on global scope, you can use:

$(o).test({
    default: true
}).on("click", function (e) {
    stopf(e);
    window["func" + v[0]](v[1], v[2]);
}

Put the functions in an object:

var funcs = {
    1: function() { func1(v[1]); },
    2: function() { func2(v[1]); },
    3: func3,
    4: func4,
    5: function() { funct5(v[1], v[2]); }
};

Then use this when binding the click handler:

$(o).test({default: true}).on("click", function(e) {
    stopf(e);
    funcs[v[0]]();
});

Notice that you have to wrap all the calls with function() { ... }. Otherwise, you'll call the function when you're assigning the variable, not when the event is triggered.


Eighter you have to declare it as an inline function:

switch(v[0]){
    case 1: myfunc=function(v[1]){ /* do something 1 */ }; break;
    case 2: myfunc=function(v[1]){ /* do something 2 */ }; break;
    case 3: myfunc=function(){ /* do something 3 */ }; break;
    case 4: myfunc=function(){ /* do something 4 */ }; break;
    case 5: myfunc=function(v[1],v[2]){ /* do something 5 */ }; break;
}

or you declare them first (seems like you already have the functions) and in my opinion this is more readable:

var func1 = function(p){ /* do something 1 */ };
var func2 = function(p,q){ /* do something 2 */ };

// and use the switch statement like this:

switch(v[0]){
  case 1: myfunc=func1; break;
  case 2: myfunc=func2; break;
}

If those parameters are important, this should make A. Wolff's work more properly:

$(o).test({default:true}).on("click",function(e){stopf(e);
    window["func" + v[0]](v[0] == (1 && 2 && 5) ? v[1] : null, v[0] == 5 ? v[2] : null);}