2

I have an array like var mya = ["someval1", "someotherval1", "someval2", "someval3"];, and I have a function that receives an object with a property set to one of those names.

It makes sense to iterate over the array and for each one check if I can find it in the array, like in a for statement. But it seems like a more efficient method would use a switch statement in this case, because the array is static and the task when I find the property is dependent on which property is found.

How do I do this with a switch array? Something like this pseudo code:

switch(mya.forEach) { 
    case "someval1": 
        alert("someval1"); 
        break; 
    ... 
    default: 
        alert("default"); 
        break; 
}

but this only calls once.

Both answers given are the code I already have — I guess there is no cleaner foreach formulation of switch.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
roberto tomás
  • 4,435
  • 5
  • 42
  • 71

3 Answers3

5
for( var i=0; i<mya.length; i++ ){
    switch( mya[i]) { 
        case "someval1": 
            alert("someval1"); 
            break; 
        ... 
        default: 
            alert("default"); 
            break; 
    }
}
sanchez
  • 4,519
  • 3
  • 23
  • 53
1

Because switch isn't foreach.

for (var i in mya)
{
    switch (mya[i])
    {
        ...
    }
}
Cobra_Fast
  • 15,671
  • 8
  • 57
  • 102
1

Given that you considered using forEach I'm assuming you're not too concerned with supporting older browsers, in which case it'd make far more sense to use Array.indexOf():

var mya = ["someval1", "someotherval1", "someval2", "someval3"],
    returnedFunctionValue = returnRandomValue();

console.log('Searching for: "' + returnedFunctionValue + '."');

if (mya.indexOf(returnedFunctionValue) > -1) {
    // the value held by the returnedFunctionValue variable is contained in the mya array
    console.log('"' + returnedFunctionValue + '" at array-index: ' + mya.indexOf(returnedFunctionValue));
}
else {
    // the value held by the returnedFunctionValue variable is not contained in the mya array
    console.log('"' + returnedFunctionValue + '" not held in the array');
}

Simple JS Fiddle demo.

Although you could, of course, use Array.prototype.forEach (in modern browsers):

var mya = ["someval1", "someotherval1", "someval2", "someval3"],
    returnedFunctionValue = returnRandomValue();

mya.forEach(function(a, b){
    if (a === returnedFunctionValue) {
        console.log('Found "' + returnedFunctionValue + '" at index ' + b);
    }
});

Simple JS Fiddle demo.

David Thomas
  • 249,100
  • 51
  • 377
  • 410