简体   繁体   中英

Javascript switch with global variable

I'm trying to use a global variable with a switch statement but the value of the variable is not changing. Perhaps a scope problem?

I need a switch statement to cycle through each case one by one, but the "i" variable keeps resetting to 1 every time I view it in the console.

Why is this happening?

THE CODE

var i = 0;

switch(i){
    case 0:
        i+=1;
        console.log(i);
        break;
    case 1:
        i+=1;
        console.log(i);
        break;
}

and so on...

edit: Great support from everybody below, thank you very much.

This behaves this way, because switch is working like:

  1. Before iteration it stores your condition.
  2. After that it takes decision.

Switch is not like "use it async", it is running only 1 time when it is invoked.

You can workaround this for example by using loop.

Use:

switch (Number(i)) {
  // cases
}

I had the same problem and had already corrected this once, but had forgotten.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM