Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find if x equals any value in an array in javascript [duplicate]

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!

like image 297
user2468491 Avatar asked Sep 03 '13 09:09

user2468491


3 Answers

You can use

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

or

if([a,b,c,d,e].indexOf(x) !== -1) {
    // ...
}
like image 99
Ingo Bürk Avatar answered Oct 03 '22 23:10

Ingo Bürk


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.

like image 35
Shivam Avatar answered Oct 03 '22 23:10

Shivam


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

like image 31
joao Avatar answered Oct 04 '22 01:10

joao