4 に答える
コードを配列に入れるだけで、値が配列にあるかどうかを簡単に確認できます。jQueryを使用しているので、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);
}
処理したくないキーの「マップ」を作成できます。実装に応じて、マップルックアップは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);
});
または、「キー」はすべて整数であるため、インデックスがキーコード値である配列を埋めることができます。
@bažmegakapaによって提案されたように、EDITは文字列を削除しました
あなたが持っているものは大丈夫です。それは明らかであり、かなり効率的に処理されます。または、次のコマンドで実行できます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を使用しているため、代わりに使用してください。
IMHO it's more clear to use the code you pointed out, but for your convenience you can use the conditions inside the case...
case (condition):
//code
break;
Personally I would put all the possible matches into an array and use in_array() from phpjs.org to check if the value to be tested is there.