Javascript shorthand if

后端 未结 5 2150
醉酒成梦
醉酒成梦 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: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.

提交回复
热议问题