Ali Ali - 7 months ago 12
Javascript Question

jQuery check in array and return true or false

I have an array of pages

var $pages = ["events", "template", "privacy", "terms", "mentor", "party", "getinvolved", "tools"];


What I want to do is

if ( $body[0].id !== anyOfThePageInTheArray ) {
//do something here
});


How can I do like if the page that they are on is not one of the page that is in the array.

I have tried
.inArray
and
.each
but I think maybe I'm doing it wrong or something.

Answer

The native Array.indexOf works fine:

if ($pages.indexOf($body[0].id) === -1) {
    // It's not in there
}

But if you insist on jQuery:

if ($.inArray($body[0].id, $pages) === -1) {
    // It's not in there
}