最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Javascript shorthand if - Stack Overflow

programmeradmin3浏览0评论
if (event.keyCode === 38 || event.keyCode === 33 || event.keyCode === 40 || event.keyCode === 34) {
}

How to shorthand this code? Remember that conditional switch statements are slow.

I want to do something like

if (event.keyCode === 38 || 33 || 40 || 34)
if (event.keyCode === 38 || event.keyCode === 33 || event.keyCode === 40 || event.keyCode === 34) {
}

How to shorthand this code? Remember that conditional switch statements are slow.

I want to do something like

if (event.keyCode === 38 || 33 || 40 || 34)
Share Improve this question edited May 23, 2017 at 12:06 CommunityBot 11 silver badge asked Nov 27, 2013 at 19:44 Szymon TodaSzymon Toda 4,51612 gold badges44 silver badges62 bronze badges 19
  • 16 Remember that conditional switch statements are slow Huh? – SLaks Commented Nov 27, 2013 at 19:45
  • 1 You want to shorten it for what? Execution time? number of characters? Is there actually a problem with what you have? – jcsanyi Commented Nov 27, 2013 at 19:47
  • 3 Yes, could you explain that? I remember a bug in Mozilla's implementation that caused switch to be slower than if/else in certain cases, but I don't understand "conditional switch statements are slow" as a general statement... – Mark Reed Commented Nov 27, 2013 at 19:49
  • 2 To people minusing this question, be so polite and state why. – Szymon Toda Commented Nov 27, 2013 at 19:53
  • 1 I have no idea why people would downvote this question. It's a good question and the answers are informative and useful. Favorited and +1 – cssyphus Commented Nov 27, 2013 at 19:56
 |  Show 14 more ments

5 Answers 5

Reset to default 13

I actually remend 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])

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]) { ... }

You could use an object lookup.

if ({33:true,34:true,38:true,40:true}[event.keyCode]) {
    ...
}

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

[B, C].includes(A)

Your example:

[38, 33, 40, 34].includes(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.

发布评论

评论列表(0)

  1. 暂无评论