switch语句是javascript中一种多分支的选择结构,它可以根据表达式的值来选择执行不同的代码分支。switch语句的语法如下:
switch (expression) {
case value1:
// Code to execute if expression = value1
break;
case value2:
// Code to execute if expression = value2
break;
...
default:
// Code to execute if expression is not equal to any of the values
}
switch语句的表达式可以是任何类型的表达式,它的值将与case子句中的值进行比较,如果匹配,则执行相应的代码,如果没有匹配,则执行default子句中的代码。
switch语句的使用方法如下:
1. 判断一个值是否在一定范围内
var x = 5;
switch (x) {
case 1:
case 2:
case 3:
case 4:
console.log('x is between 1 and 4');
break;
case 5:
case 6:
case 7:
case 8:
console.log('x is between 5 and 8');
break;
default:
console.log('x is not between 1 and 8');
}
在上面的例子中,我们可以看到,switch语句用于判断一个值是否在一定范围内,如果x的值在1-4之间,则执行第一个case子句,如果x的值在5-8之间,则执行第二个case子句,如果x的值不在1-8之间,则执行default子句。
2. 判断一个字符串是否匹配某一个值
var color = 'red';
switch (color) {
case 'red':
console.log('color is red');
break;
case 'blue':
console.log('color is blue');
break;
case 'green':
console.log('color is green');
break;
default:
console.log('color is not red, blue or green');
}
在上面的例子中,我们可以看到,switch语句用于判断一个字符串是否匹配某一个值,如果color的值是red,则执行第一个case子句,如果color的值是blue,则执行第二个case子句,如果color的值是green,则执行第三个case子句,如果color的值不是red、blue或green,则执行default子句。
3. 判断一个变量的类型
var x = 5;
switch (typeof x) {
case 'number':
console.log('x is a number');
break;
case 'string':
console.log('x is a string');
break;
case 'boolean':
console.log('x is a boolean');
break;
default:
console.log('x is not a number, string or boolean');
}
在上面的例子中,我们可以看到,switch语句用于判断一个变量的类型,如果x是一个数字,则执行第一个case子句,如果x是一个字符串,则执行第二个case子句,如果x是一个布尔值,则执行第三个case子句,如果x不是数字、字符串或布尔值,则执行default子句。
以上就是javascript中switch语句的使用方法,switch语句可以帮助我们更快更简单的完成多分支的选择结构,使代码更加简洁。