Home > Web Front-end > JS Tutorial > body text

Usage examples of JavaScript switch case [scope]_javascript skills

WBOY
Release: 2016-05-16 18:46:06
Original
1857 people have browsed it
A few examples:
Copy code The code is as follows:

function case1 (num){
switch(num){
case 1:
document.writeln("show 1!!");
break;
case 2:
document.writeln ("show 2!!");
break;
case 3:
document.writeln("show 3!!");
break;
default:
document. writeln("show others!!");
break;
}
}
function case2(num){
switch(num){
case 1:
document .writeln("show 1!!");
//There is no break, so case 2 will continue to be executed
case 2:
document.writeln("show 2!!");
break ;
case 3:
document.writeln("show 3!!");
//There is no break, so case 4 will continue to be executed
case 4:
document.writeln(" show 4!!");
break;
default:
document.writeln("show others!!");
break;
}
}
function case3 (num){
switch(num){
case 1:
case 2:
//Equivalent to if(num==1 || num==2)
document.writeln ("show 1 or 2!!");
break;
case 3:
case 4:
//Equivalent to if(num==3 || num==4)
document.writeln("show 3 or 4!!");
break;
default:
//Equivalent to else
document.writeln("show others!!");
break;
}
}
function case4(num){
switch(f(num)){
case 1:
case 2:
//Equivalent if(num==1 || num==2)
document.writeln("show 1 or 2!!");
break;
case 3:
case 4:
//equivalent to if(num==3 || num==4)
document.writeln("show 3 or 4!!");
break;
default:
//equivalent in else
document.writeln("show others!!");
break;
}
}
function f(num){
return num;
}
function case5(num){
switch(num<=2){
case true:
document.writeln("num <= 2");
break;
case false:
document.writeln("num > 2");
break;
}
}

JavaScript switch case statement setting range

[Ctrl A select all Note: If you need to introduce external Js, you need to refresh to execute
]<script> var x=10 switch(true){ case x>0&&x<10: alert(1); break; case x>=10&&x<20: alert(2); break; } </script>
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template