Skip to main content
June 4, 2015
Answered

Multiple if checks to 1 variable

  • June 4, 2015
  • 1 reply
  • 290 views

Is there another way to code this? Comparing a variable (var1) to multiple values.

if(var1 != array[0] && var1 != array[1] && var1 != array[2]) {}

Is there some other way to code that? Like if(var1 != (array[0] && array[1] && array[2]) ) {}

I know that doesn't work, but is there another way to code it?

This topic has been closed for replies.
Correct answer Ned Murphy

If you are checking the entire array then you could use....

if(array.indexOf(var1) == -1) {  }

indexOf() checks to see if var1 exists in the array and if it does not it will return -1,   otherwise it returns the index of the array holding the value of var1

1 reply

Ned Murphy
Ned MurphyCorrect answer
Legend
June 4, 2015

If you are checking the entire array then you could use....

if(array.indexOf(var1) == -1) {  }

indexOf() checks to see if var1 exists in the array and if it does not it will return -1,   otherwise it returns the index of the array holding the value of var1

June 4, 2015

Another wonderful leading answer. Wasn't looking for array checking specifically but that works fine just fine.

if( new Array( valueX, valueY, vallueZ ).indexOf( var1 ) > -1 ) { }

--Added--

Had a feeling so did a test, new Array().indexOf() takes significantly longer then manually doing var1 == var2 || var1 == ... so gonna have to stick with the original for now.

looped 10k times

~25ms: new Array( 1, 2, 3, 4, 5 ).indexOf(3)

~10ms: myArray.indexOf(3)

~1ms: 1== 1||1== 2||1== 3||1== 4||1== 5

But thanks for the info, I enjoy learning new ways to do things.