Javascript shorthand if

后端 未结 5 2128
醉酒成梦
醉酒成梦 2020-12-10 10:09
if (event.keyCode === 38 || event.keyCode === 33 || event.keyCode === 40 || event.keyCode === 34) {
}

How to shorthand this code? Remember that con

相关标签:
5条回答
  • 2020-12-10 10:36

    You could use an object lookup.

    if ({33:true,34:true,38:true,40:true}[event.keyCode]) {
        ...
    }
    
    0 讨论(0)
  • 2020-12-10 10:37

    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.

    0 讨论(0)
  • 2020-12-10 10:46

    Here's an improved solution that uses ES6 Array.prototype.includes():

    [B, C].includes(A)
    

    Your example:

    [38, 33, 40, 34].includes(event.keyCode)

    0 讨论(0)
  • 2020-12-10 10:48

    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]) { ... }
    
    0 讨论(0)
  • 2020-12-10 10:54

    I actually recommend using a switch. The general rule of thumb is

    • 1 or 2 values: use an if
    • 3 to 10 values: use a switch
    • 11 or more: use an array lookup

    But since you're using jQuery, you can simply do:

    jQuery.inArray(event.keyCode, [38,33,40,34])
    
    0 讨论(0)
提交回复
热议问题