Dynamically adding cases to a switch

后端 未结 2 1895
情书的邮戳
情书的邮戳 2020-12-03 08:44

I need to dynamically add cases to a switch. I want the user to be able to add items and every item needs it\'s own switch case.

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-03 09:10

    This was the best solution for my needs, but works only with a limited number of custom cases:

    var cases = [false, false];
    
    switch(condition) {
        case cases[0]:
            doStuff();
            break;
        case cases[1]:
            doSomethingElse();
            break;
    }
    

    Now, you can dynamically change the values in the array cases, and the condition in the switch case will be triggered respectively;

    You can click the above snippet to see it working ;)

    const cases = [false, false]; // shall be defined
      
    $('#option1').click( function() {
      cases = [38,37];
    });
    
    $('#option2').click( function() {
      cases = [39,40];
    });
    
    $(window).keydown( function(e) {
      switch (e.keyCode) {
         case 32:
            $("body").append('space
    '); break; case cases[0]: $("body").append((e.keyCode == '38' ? 'UP' : 'RIGHT' ) + '
    '); break; case cases[1]: $("body").append((e.keyCode == '37' ? 'LEFT' : 'DOWN' ) + '
    '); break; } });
    
    
    At the begining the switch only take in account SPACE keyCode
    -if you click option1 then it recognize UP and LEFT
    -if you click option2, the aboves are replaced with RIGHT and DOWN

    OPTION 1
    OPTION 2

提交回复
热议问题