Switch语句:如果第二种情况不等于0,那么是什么导致第二种情况运行呢?

I do something like the pomodoro technique, and I have a specific recovery routine. Coffee, V8, and yoga after three pomodoros. A twenty minute nap after four. Why not everything at four pomodoros? ...Reasons. I created this switch statement to decide what recovery to propose. const numPomodoros = 3; // It checks the # of pomodoros in the db, but I'm setting it to 3 to illustrate the problem. switch (0) { case numPomodoros % 3: console.log('I propose coffee, V8, and 5m of yoga.'); case numPomodoros % 4: console.log('I propose a 20m nap.'); } I expected only the first case to run (3 % 3 === 0, should run; 4 % 3 === 1, should not run); however, the second case always runs: $ node index.js s I propose coffee, V8, and 5m of yoga. I propose a 20m nap. What's causing the second case to run if it doesn't equal 0 like in the switch conditional says it should?


You need to add a break instruction. It will stop the execution of inside the block. No break means that the code keeps running. May be you need a default to. If you want a default action "Like unknown value" const numPomodoros = 3; // It checks the # of pomodoros in the db, but I'm setting it to 3 to illustrate the problem. switch (0) { case numPomodoros % 3: console.log('I propose coffee, V8, and 5m of yoga.'); break; case numPomodoros % 4: console.log('I propose a 20m nap.'); break; }

Node.js skips over code in the switch statement until it matches one case. When it matches a case, it stops checking against cases and waterfalls down, executing code until it sees a break or a }. For this situation, use if-then. const numPomodoros = 3; // Or what the db count shows. if (numRecoveries % 3 === 0) console.log('I propose coffee, V8, and 5m of yoga.'); if (numRecoveries % 4 === 0) console.log('I propose a 20m nap.'); Outputs: $ node index.js s I propose coffee, V8, and 5m of yoga.

If you don't put a break at the end of the case block,all the following case blocks will be executed too. Also you should put a default case at the end to handle the cases that aren't matched by any of the previous blocks. This is the working version: const numPomodoros = 3; // It checks the # of pomodoros in the db, but I'm setting it to 3 to illustrate the problem. switch (0) { case numPomodoros % 3: console.log('I propose coffee, V8, and 5m of yoga.'); break; case numPomodoros % 4: console.log('I propose a 20m nap.'); break; default: console.log("Default case."); break; }