Is there a better way to deal with checking multiple values. It starts to get really busy when I have more than 3 choices.
if (myval=='something' || myval=='other' || myval=='third') {
}
PHP has a function called in_array()
that's used like this:
in_array($myval, array('something', 'other', 'third'))
Is there something like it in js or jquery?
Is there a better way to deal with checking multiple values. It starts to get really busy when I have more than 3 choices.
if (myval=='something' || myval=='other' || myval=='third') {
}
PHP has a function called in_array()
that's used like this:
in_array($myval, array('something', 'other', 'third'))
Is there something like it in js or jquery?
Share Improve this question asked Apr 8, 2011 at 19:33 jarnjarn 2631 gold badge2 silver badges8 bronze badges4 Answers
Reset to default 6Jquery.inArray()
Besides $.inArray
, you could use Object notation:
if (myval in {'something':1, 'other':1, 'third':1}) {
...
or
if (({'something':1, 'other':1, 'third':1}).hasOwnProperty(myval)) {
....
(Note that the 1st code won't work if the client side has modified Object.prototype
.)
You can avoid iterating over the array by using some kind of a hash map:
var values = {
'something': true,
'other': true,
'third': true
};
if(values[myVal]) {
}
Does also work without jQuery ;)
a clean solution taken from the 10+ JAVASCRIPT SHORTHAND CODING TECHNIQUES:
longhand
if (myval === 'something' || myval === 'other' || myval === 'third') {
alert('hey-O');
}
shorthand
if(['something', 'other', 'third'].indexOf(myvar) !== -1) alert('hey-O');