2

I have an array that will be populated with an unknown number of elements.

myArray = ["a", "b", "c",...]

I want to create a switch statement so that it contains all the cases contained in myArray.

The outcome I would like is something like:

switch (true) {
    case myVariable === 'a':
    // DO something
    break
    case myVariable === 'b':
    // DO something
    break
    ... KEEP REPETING FOR EACH ELEMENT IN myArray
}

Clearly, I cannot hardcode all the cases because I do not know how many there are and how they are called.

My idea was to create a loop inside the switch as follow:

switch (true) {
    myArray.map(myElement => {
    case myVariable === myElement:
    // DO something
    break
    })
}

I do not think this is possible because switch expects a case not a .map

I check this answer Dynamically adding cases to a switch but it does not address the loop part

6
  • Maybe you do to not need switch at all? Why not just use map? Commented Jul 21, 2020 at 11:04
  • Is it a "use switch or die" situation? I would like to think this is when a for loop would suffice. Commented Jul 21, 2020 at 11:08
  • 1
    What is the action for each case ? If variable is "a", what action do you want to perform, if variable is "b" what action you want to have in case. How are actions defined ? Commented Jul 21, 2020 at 11:10
  • 1
    You could do it with eval(). However I would not recommend to use that since it has downsides because of security and performance. As others mentioned a simple loop would do the trick too. Commented Jul 21, 2020 at 11:13
  • We need to know how the functions (and their respective arguments, if any) are associated with the elements of myArray. For example, do you start with three parallel arrays (cases, functions, arguments)? Or does my array contain objects that hold all three pieces of information for a given case? Or are the functions actually "parameterless" methods whose names exactly match the case strings?... Commented Jul 21, 2020 at 11:22

1 Answer 1

1

You can't do that.

What you're probably looking for is just to iterate on every element in the array, check the condition, and act accordingly.

myArray.map(myElement => {
    if (condition)
    {
        //Do something
    }
})

That's the best way I can think of.

Sign up to request clarification or add additional context in comments.

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.