-1

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

Adacho
  • 99
  • 4
  • 13

2 Answers2

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

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

zerkms
  • 249,484
  • 69
  • 436
  • 539
  • But are you sure this works in all browsers? In the "compatibility" section it says it might not be available in all browsers. – mohkhan Jul 07 '13 at 08:36
  • @mohkhan: 1. there are a list of supported browsers on the link 2. There is a shim function definition for the browsers don't have its support natively – zerkms Jul 07 '13 at 08:38
0

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.

Daniel Kmak
  • 18,164
  • 7
  • 66
  • 89