开发者

Variables in javascript switch cases?

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

switc开发者_运维百科h(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.


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜