Less lines for switch statement?

I wonder if this is ...

inputs.keydown(function (e) {
    switch (e.keyCode) {
        case 13:    //Enter
        case 16:    //Shift
        case 17:    //Ctrl
        case 18:    //Alt
        case 19:    //Pause/Break
        case 20:    //Caps Lock
        case 27:    //Escape
        case 35:    //End
        case 36:    //Home
        case 37:    //Left
        case 38:    //Up
        case 39:    //Right
        case 40:    //Down

        // Mac CMD Key
        case 91:    //Safari, Chrome
        case 93:    //Safari, Chrome
        case 224:   //Firefox
        break;
        default:
        $(this).addClass(fill);
        break;
    }
});

... also possible with fewer lines? I know I can make an if condition, but I wonder if I missed something likecase 13 && 16 && …

Perhaps some of you know that it’s better to check all cases and write fewer lines of code. I'm just curious.

Thank you in advance!

+3
source share
4 answers

Just put the codes in an array, and then you can just check if that value is in the array. Since you are using jQuery, you already have a method inArray().

var keycodes = [13, 16, 17, 18, 19]; //and so on

//if the keycode is not found in the array, the result will be -1
if ($.inArray(e.keyCode, keycodes) === -1) { 
    $(this).addClass(fill);
}
+7
source

"" , , - - O(1) O(log n), .

var specialKeys = {
    13: 1, // Enter
    16: 1, // Shift
    ...
    224: 1 // Cmd/FF
};

inputs.keydown(function (e) {
    if (e.keyCode in specialKeys) return;
    $(this).addClass(fill);
});

, "" - , , key code.

EDIT , @bažmegakapa

+8

. , . Array#indexOf:

var list1 = [
        13,    //Enter
        16,    //Shift
        17,    //Ctrl
        18,    //Alt
        19,    //Pause/Break
        20,    //Caps Lock
        27,    //Escape
        35,    //End
        36,    //Home
        37,    //Left
        38,    //Up
        39,    //Right
        40     //Down
];
var list2 = [
        91,    //Safari, Chrome
        93,    //Safari, Chrome
        224    //Firefox
];
inputs.keydown(function (e) {
    if (list1.indexOf(e.keyCode) !== -1) {
        // ...
    }
    else if (list2.indexOf(e.keyCode) !== -1) {
        // ...
    }
    else {
        $(this).addClass(fill);
    }
});

"" ​​, , .

, Array#indexOf, , , ( ). jQuery.inArray , jQuery.

+2

, , , ...

case (condition):
//code
break;

Personally, I would put all possible matches into an array and use in_array () from phpjs.org to check if there is a test value.

0
source

All Articles