JavaScript switch 语句 JavaScript switch 语句switch 语句用于基于不同的条件来执行不同的动作。JavaScript switch 语句 请使用 switch 语句来选择要执行的多个代码块之一。 语法 switch (n) { case 1: 执行代码块 1 break; case 2: 执行代码块 2 break; default: 与case 1 和case 2 不同时执行的...
//this code will execute if the case matches the expression break; case 2: //this code will execute if the case matches the expression break; case 3: //this code will execute if the case matches the expression break; default: //this code will execute if none of the cases match the e...
// 嵌套的 if/else 导致代码难以阅读functiongetDiscount(user){if(user.type==='premium'){if(user.years>5)return0.25;elsereturn0.15;}elseif(user.type==='standard'){if(user.years>3)return0.10;elsereturn0.05;}else{return0;}}// 冗长的 switch 语句functiongetColorCode(color){switch(color){case...
switch(expression) { case n: code block break; case n: code block break; default: default code block }参数值参数描述 expression 必需。指定要计算的表达式。表达式会被计算一次。表达式的值与结构中每个 case 标签的值进行比较。如果匹配,则执行相关的代码块。技术细节JavaScript 版本: ECMAScript 1更多实例...
He shows two styles for "switching", one of witch is so close to a similar pattern in Python. Python has no switch, and it can teach us a better alternative to our beloved, cluttered switch. Let's first port our code from JavaScript to Python: LOGIN_SUCCESS = "LOGIN_SUCCESS"LOGIN_...
switch(expression or literal value){ case 1: //code to be executed break; case 2: //code to be executed break; case n: //code to be executed break; default: //default code to be executed //if none of the above case executed }Use...
In this example case 4 and 5 share the same code block, and 0 and 6 share another code block: Example switch(newDate().getDay()) { case4: case5: text ="Soon it is Weekend"; break; case0: case6: text ="It is Weekend"; ...
In addition toif...else, JavaScript has a feature known as aswitchstatement.switchis a type of conditional statement that will evaluate an expression against multiple possible cases and execute one or more blocks of code based on matching cases. Theswitchstatement is closely related to a conditio...
In the code below, we accomplish this idea with the help of switch: JavaScript var code = Number(prompt('Enter an HTTP response code:')); var msg; switch (code) { case 200: msg = 'OK'; break; case 302: msg = 'Found'; break; case 404: msg = 'Not Found'; break; case 500:...
The JavaScript Switch StatementUse the switch statement to select one of many blocks of code to be executed.Syntaxswitch(expression) { case n: code block break; case n: code block break; default: default code block } This is how it works:The switch expression is evaluated once. The value...