0

I want to use variables as the values for each case in a switch statement, but it doesnt seem to work:

switch(key) {  

    case keyNext: 
      //go to next
      break;

    case keyPrev: 
      //go to prev
      break;
}

I really need the switch statement because unlike in this example, I have lots of different cases.

Why doesnt this work? Any workarounds for it?

EDIT: as said in the answers, this is perfectly valid. I was using properties of an object as the values for each case, and there was a syntax problem with it.

2
  • What is key? Is it event.keycode? Your switch is syntactically correct, but how are you mapping keycodes to keyNext, keyPrev? Are they defined by a framework? Commented Sep 2, 2011 at 13:10
  • Your code seems ok... Maybe add a snippet of some of your cases so I can help better? Since you have a lot of cases, maybe you have a syntax error somewhere Commented Sep 2, 2011 at 13:13

1 Answer 1

1

You can use variables to check against, see the following example. You just need to make sure they are declared and given a value. May need to see more of what your working with to see if the issue is arising elsewhere.

Live Demo

var keyNext = 1, // or "1" what have you,
    keyPrev = 2,
    key = keyPrev; // or key = 1

switch(key) {  

    case keyNext: 
      alert('Next');
      break;

    case keyPrev: 
      alert('Prev');
      break;
}
Sign up to request clarification or add additional context in comments.

1 Comment

I see. Then my problem is somewhere else. My variables are actually properties of an object (I tried to simplify the question since I thought it was the same). Like appname.config.keyNext instead of keyNext. That should work too, right?

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.