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.

3 Answers 3

5
for( var i=0; i<mya.length; i++ ){
    switch( mya[i]) { 
        case "someval1": 
            alert("someval1"); 
            break; 
        ... 
        default: 
            alert("default"); 
            break; 
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Cobra_fast was prettier, but yours was also correct and first. I'll give it in 8 minutes.
1

Because switch isn't foreach.

for (var i in mya)
{
    switch (mya[i])
    {
        ...
    }
}

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.