12

I currently have an if statement like this:

if (x==a||x==b||x==c||x==d||x==e) {
   alert('Hello World!')
};

How can I instead test if x equals any value in an array such as [a,b,c,d,e]?

Thank you!

Paritosh
  • 10,474
  • 4
  • 54
  • 71
user2468491
  • 121
  • 1
  • 1
  • 6

4 Answers4

26

You can use

if([a,b,c,d,e].includes(x)) {
    // ...
}

or

if([a,b,c,d,e].indexOf(x) !== -1) {
    // ...
}
Ingo Bürk
  • 17,703
  • 6
  • 60
  • 91
3

You can use the following code:

<script>
    var arr = [ 4, "Pete", 8, "John" ];
    var $spans = $("span");
    $spans.eq(0).text(jQuery.inArray("John", arr));
    $spans.eq(1).text(jQuery.inArray(4, arr));
    $spans.eq(2).text(jQuery.inArray("Karl", arr));
    $spans.eq(3).text(jQuery.inArray("Pete", arr, 2));
</script>

Read this link for more information about it

Hope this helps you.

Sarvan
  • 698
  • 8
  • 16
Shivam
  • 647
  • 1
  • 4
  • 24
1

check out jquery function inArray(): http://api.jquery.com/jQuery.inArray/

joao
  • 334
  • 2
  • 9
  • 5
    Because, of course, [jQuery is the answer to everything](http://www.doxdesk.com/img/updates/20091116-so-large.gif) – Niet the Dark Absol Sep 03 '13 at 09:46
  • why did i get a down vote? i stated a possibility you only use it if you want. It is a correct anwser – joao Sep 03 '13 at 09:58
  • 3
    I didn't downvote, but suggesting one use jQuery when there are extremely simple [Vanilla JS](http://vanilla-js.com/) solutions to the problem is like using a sledgehammer to lightly tap a nail so you can hang a painting. – Niet the Dark Absol Sep 03 '13 at 09:59
  • 1
    You stated a solution with indexOf that is not implemented for arrays in IE<9. This is a simple cross/browser solution. I don't think jquery is solution to everything but to some simple things i rather have a cross/browser guaranteed solution... – joao Sep 03 '13 at 10:06
  • My solution includes a simple fallback for browsers where `haystack.indexOf` doesn't exist. – Niet the Dark Absol Sep 03 '13 at 10:46
1

Try this helper function:

function in_array(needle,haystack) {
    if( haystack.indexOf) return haystack.indexOf(needle) > -1;
    for( var i=0, l=haystack.length, i<l; i++) if(haystack[i] == needle) return true;
    return false;
}

This makes use of the built-in indexOf if available, otherwise it iterates manuatlly.

Niet the Dark Absol
  • 311,322
  • 76
  • 447
  • 566
  • It might be better to use ES5 shim for this - that way, once you drop IE8 support, you can remove the shim and the code won't have to change. – mikemaccana Sep 03 '13 at 09:58