0

Is it possible to test a variable against a specific/all possible values within an array? For instance, if I have:

var abc;
var array1 = ["item1", "item2", "item3"];

function someFunction(){
  abc = "item2"
  if (abc == !!**Either array1[item1] OR array1[item2] OR.. etc for x in array1**!!)
    {
      //*do stuff*
    }
}

What is the correct syntax for testing abc against any possible entry in array1?

Alexander Karmes
  • 2,438
  • 1
  • 28
  • 34
acdhyut
  • 3
  • 1
  • 2
    If you're just talking simple strings, see [this question](http://stackoverflow.com/questions/237104/array-containsobj-in-javascript) for lost of ways to do a "contains" in javascript. – Joe Enos Oct 22 '14 at 21:40

3 Answers3

0

There is no syntax for this, you need to loop over the array and compare values indiviually.

function  somefunction(){
  abc = "item2"

  for (var i = 0; i < array1.length; ++i) {
    if (abc == array1[i]) {
      //*do stuff*
    }
  }
}

A common way of shortening this (in the case where your test is for simple equality) is to use the built-in indexOf function, which returns the index of the item in the array, or -1 if it wasn't found.

if (array1.indexOf(abc) != -1) { ... }
user229044
  • 232,980
  • 40
  • 330
  • 338
0

I suggest using a loop:

for(i in array1){
  if(abc === array1[i]){
    // do stuff
  }
}
Carlos Pliego
  • 859
  • 1
  • 8
  • 19
  • 3
    Be careful when using `for .. in` - if you've defined anything in the prototype, you'll get unexpected results - see [this question](http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea) – Joe Enos Oct 22 '14 at 21:43
0

Use indexOf() to check what position the value appears at in the array. If it returns -1, then the value doesn't exist.

if (array1.indexOf(abc) != -1) {
  // do stuff...
}
danmullen
  • 2,556
  • 3
  • 20
  • 28