Reputation: 21212
I have an array 'iid_nn' which will contain ~ 50 values.
If iid_nn contains either 13652 or 39855, then var somevar = 'cabbages' else var somevar = 'carrots'.
If checking for one of those values I could do
if(iid_nn.indexOf(13652) >=0) {
var somevar = 'cabbages';
} else if(iid_nn.indexOf(39855) >=0) {
{var somevar = 'cabbages';
} else {
var somevar = 'carrots';}
But can I do something like
if(iid_nn.indexOf(13652||39855) >=0) {
var somevar = 'cabbages';
} else {
var somevar = 'carrots';
}
Upvotes: 1
Views: 47
Reputation: 386570
var iid_nn = [13652],
somevar;
if (~iid_nn.indexOf(13652) || ~iid_nn.indexOf(39855)) {
somevar = 'cabbages';
} else {
somevar = 'carrots';
}
Upvotes: 0
Reputation: 36609
Try this:
if((iid_nn.indexOf(13652) !=-1)||(iid_nn.indexOf(39855) !=-1)) {
var somevar = 'cabbages';
} else {
var somevar = 'carrots';
}
Upvotes: 0
Reputation: 1946
Your condition is kind of wrong.
if(iid_nn.indexOf(39855)!=-1 || iid_nn.indexOf(13652)!=-1)
{
var somevar = 'cabbages';
} else {
var somevar = 'carrots';
}
Upvotes: 0
Reputation: 28455
To check index of multiple values, you need to update your code to following. Additionally, you can default the value to carrots and then on condition update it.
var somevar = 'carrots';
if(iid_nn.indexOf(13652) >= -1 || iid_nn.indexOf(39855) >= -1) {
somevar = 'cabbages';
}
Upvotes: 0
Reputation: 224903
You can’t pass one value to indexOf
that will cause it to search for multiple values. You can use the ||
operator normally, though:
var somevar;
if (iid_nn.indexOf(13652) >= 0 || iid_nn.indexOf(39855) >= 0) {
somevar = 'cabbages';
} else {
somevar = 'carrots';
}
And maybe create your own function to do it:
function containsAny(array, items) {
return array.some(function (item) {
return items.indexOf(item) !== -1;
});
}
var somevar;
if (containsAny(iid_nn, [13652, 39855])) {
somevar = 'cabbages';
} else {
somevar = 'carrots';
}
Upvotes: 2
Reputation: 20063
You can either modify your indexOf
conditional to be:
if (iid_nn.indexOf(13652) > -1 || iid_nn.indexOf(39855) > -1) {
Or you can try using array.some.
if (iid_nn.some(function(i) { return i === 13652 || i === 39855; }) === true) {
Upvotes: 2