Question

how to check that the variable occurs in an array?

In Example

var X = 5;
var newArray = [1,2,5]

And now something like this

if(X.isin(newArray)
{ document.write( "YES");}

something like this exist? :P

Was it helpful?

Solution

if (newArray.indexOf(X) > -1) {
    // value X exists in newArray
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

OTHER TIPS

You can also use JQuery's inArray() method - it solves compatibility problems. Code:

var X = 5;
var newArray = [1,2,5]
if ($.inArray(X, newArray) > -1) {
    alert('is in array');
}

Fiddle.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top