if (event.keyCode === 38 || event.keyCode === 33 || event.keyCode === 40 || event.keyCode === 34) {
}
How to shorthand this code? Remember that con
You could use an object lookup.
if ({33:true,34:true,38:true,40:true}[event.keyCode]) {
...
}
You can use regular expressions, although I'm not sure if that's necessarily faster than a switch statement.
if (/^(38|33|40|34)$/.test(event.keyCode)) {
// Some code here
}
Though it's much more readable than doing an object property look-up.
Here's an improved solution that uses ES6 Array.prototype.includes():
[B, C].includes(A)
Your example:
[38, 33, 40, 34].includes(event.keyCode)
Using pure JavaScript, you could do something like this:
if ([38,33,40,34].indexOf(event.keyCode) >= 0) { ... }
But keep in mind that this method was introduced with ECMAScript 5, and so isn't supported by some older browsers.
You could also do something like this, which should work on older browsers as well:
if ({38:1,33:1,40:1,34:1}[event.keyCode]) { ... }
I actually recommend using a switch. The general rule of thumb is
But since you're using jQuery, you can simply do:
jQuery.inArray(event.keyCode, [38,33,40,34])