JavaScript switch用法
在JavaScript中,switch语句是一种用于根据不同条件执行不同代码块的控制流语句。它可以替代多个if语句,使代码更加简洁和易读。在本文中,我们将详细介绍switch语句的用法,并提供多个示例代码来帮助您更好地掌握它。
基本语法
switch语句的基本语法如下:
switch(expression) {
case value1:
// 当expression等于value1时执行的代码块
break;
case value2:
// 当expression等于value2时执行的代码块
break;
default:
// 当expression不等于任何case时执行的代码块
}
在switch语句中,expression是要进行比较的表达式,value1、value2等是可能的取值,case后面跟着的是具体的取值,default是可选的,表示当expression不等于任何case时执行的代码块。
示例代码1:基本用法
let fruit = 'apple';
switch(fruit) {
case 'apple':
console.log('I love apples!');
break;
case 'banana':
console.log('I like bananas!');
break;
default:
console.log('I am not a fan of fruits.');
}
代码运行结果:
在上面的示例中,当fruit的取值为’apple’时,输出’I love apples!’,当fruit的取值为’banana’时,输出’I like bananas!’,否则输出’I am not a fan of fruits.’。
示例代码2:多个case合并
let color = 'red';
switch(color) {
case 'red':
case 'green':
case 'blue':
console.log('This is a primary color.');
break;
default:
console.log('This is not a primary color.');
}
代码运行结果:
在上面的示例中,当color的取值为’red’、’green’或’blue’时,输出’This is a primary color.’,否则输出’This is not a primary color.’。可以看到,多个case可以合并在一起,执行相同的代码块。
示例代码3:使用break语句
let day = 'Monday';
switch(day) {
case 'Monday':
console.log('Today is Monday.');
break;
case 'Tuesday':
console.log('Today is Tuesday.');
break;
case 'Wednesday':
console.log('Today is Wednesday.');
break;
default:
console.log('Today is not a weekday.');
}
代码运行结果:
在上面的示例中,当day的取值为’Monday’时,输出’Today is Monday.’,并且使用break语句来终止switch语句的执行,避免继续执行后续case的代码块。
示例代码4:不使用break语句
let month = 'January';
switch(month) {
case 'January':
console.log('It is January.');
case 'February':
console.log('It is February.');
case 'March':
console.log('It is March.');
default:
console.log('It is not a specific month.');
}
代码运行结果:
在上面的示例中,当month的取值为’January’时,输出’It is January.’,但没有使用break语句,因此会继续执行后续case的代码块,直到遇到break或switch语句结束。
示例代码5:使用表达式作为case
let num = 3;
switch(true) {
case num > 5:
console.log('Number is greater than 5.');
break;
case num < 5:
console.log('Number is less than 5.');
break;
default:
console.log('Number is equal to 5.');
}
代码运行结果:
在上面的示例中,我们使用true作为switch语句的表达式,然后在case中使用表达式num > 5和num < 5来进行比较,根据条件输出不同的结果。
示例代码6:使用字符串作为case
let website = 'deepinout.com';
switch(website) {
case 'google.com':
console.log('This is Google.');
break;
case 'deepinout.com':
console.log('This is Deepinout.');
break;
default:
console.log('This is an unknown website.');
}
代码运行结果:
在上面的示例中,我们使用字符串’deepinout.com’作为switch语句的表达式,然后根据不同的取值输出不同的结果。
示例代码7:使用变量作为case
let x = 2;
let y = 3;
switch(x + y) {
case 5:
console.log('Sum is 5.');
break;
case 6:
console.log('Sum is 6.');
break;
default:
console.log('Sum is not 5 or 6.');
}
代码运行结果:
在上面的示例中,我们使用变量x和y的和作为switch语句的表达式,然后根据不同的取值输出不同的结果。
示例代码8:使用逻辑运算符作为case
let age = 25;
switch(true) {
case age < 18:
console.log('You are under 18.');
break;
case age >= 18 && age < 30:
console.log('You are between 18 and 30.');
break;
default:
console.log('You are over 30.');
}
代码运行结果:
在上面的示例中,我们使用true作为switch语句的表达式,然后在case中使用逻辑运算符来进行条件判断,根据不同的条件输出不同的结果。
示例代码9:使用switch语句处理不同类型
let type = 'string';
switch(typeof type) {
case 'string':
console.log('This is a string.');
break;
case 'number':
console.log('This is a number.');
break;
case 'boolean':
console.log('This is a boolean.');
break;
default:
console.log('This is not a string, number or boolean.');
}
代码运行结果:
在上面的示例中,我们使用typeof操作符获取变量type的类型,然后根据不同的类型输出不同的结果。
示例代码10:使用switch语句处理数组
let arr = [1, 2, 3];
switch(arr.length) {
case 0:
console.log('Array is empty.');
break;
case 1:
console.log('Array has 1 element.');
break;
default:
console.log('Array has more than 1 element.');
}
代码运行结果:
在上面的示例中,我们使用数组arr的长度作为switch语句的表达式,然后根据不同的长度输出不同的结果。
示例代码11:使用switch语句处理对象
let obj = {
name: 'Alice',
age: 30
};
switch(Object.keys(obj).length) {
case 0:
console.log('Object is empty.');
break;
case 1:
console.log('Object has 1 property.');
break;
default:
console.log('Object has more than 1 property.');
}
代码运行结果:
在上面的示例中,我们使用对象obj的属性数量作为switch语句的表达式,然后根据不同的属性数量输出不同的结果。
示例代码12:使用switch语句处理函数返回值
function getDayOfWeek(day) {
switch(day) {
case 0:
return 'Sunday';
case 1:
return 'Monday';
case 2:
return 'Tuesday';
case 3:
return 'Wednesday';
case 4:
return 'Thursday';
case 5:
return 'Friday';
case 6:
return 'Saturday';
default:
return 'Invalid day';
}
}
console.log(getDayOfWeek(3));
代码运行结果:
在上面的示例中,我们定义了一个函数getDayOfWeek,根据传入的参数返回对应的星期几。使用switch语句处理不同的参数值,返回不同的结果。
示例代码13:使用switch语句处理正则表达式
let str = 'deepinout.com';
let pattern = /deepinout/;
switch(true) {
case pattern.test(str):
console.log('String matches the pattern.');
break;
default:
console.log('String does not match the pattern.');
}
代码运行结果:
在上面的示例中,我们使用正则表达式pattern来匹配字符串str,然后根据匹配结果输出不同的结果。
示例代码14:使用switch语句处理日期
let date = new Date();
let dayOfWeek = date.getDay();
switch(dayOfWeek) {
case 0:
console.log('Today is Sunday.');
break;
case 1:
console.log('Today is Monday.');
break;
case 2:
console.log('Today is Tuesday.');
break;
case 3:
console.log('Today is Wednesday.');
break;
case 4:
console.log('Today is Thursday.');
break;
case 5:
console.log('Today is Friday.');
break;
case 6:
console.log('Today is Saturday.');
break;
}
代码运行结果:
在上面的示例中,我们获取当前日期的星期几,然后根据不同的星期几输出不同的结果。
示例代码15:使用switch语句处理用户输入
let userInput = prompt('Enter a number between 1 and 3:');
switch(parseInt(userInput)) {
case 1:
console.log('You entered 1.');
break;
case 2:
console.log('You entered 2.');
break;
case 3:
console.log('You entered 3.');
break;
default:
console.log('Invalid input.');
}
在上面的示例中,我们使用prompt函数获取用户输入的数字,然后根据不同的输入输出不同的结果。
示例代码16:使用switch语句处理API返回值
fetch('https://api.deepinout.com/data')
.then(response => response.json())
.then(data => {
switch(data.status) {
case 'success':
console.log('Data retrieved successfully.');
break;
case 'error':
console.log('Error retrieving data.');
break;
default:
console.log('Unknown status.');
}
});
在上面的示例中,我们使用fetch函数从API获取数据,然后根据返回的status值输出不同的结果。
示例代码17:使用switch语句处理不同浏览器
let browser = 'Chrome';
switch(browser) {
case 'Chrome':
console.log('You are using Chrome browser.');
break;
case 'Firefox':
console.log('You are using Firefox browser.');
break;
case 'Safari':
console.log('You are using Safari browser.');
break;
default:
console.log('You are using an unknown browser.');
}
代码运行结果:
在上面的示例中,我们根据不同的浏览器输出不同的结果,可以根据用户的浏览器类型进行相应的处理。
示例代码18:使用switch语句处理不同设备
let device = 'Mobile';
switch(device) {
case 'Mobile':
console.log('You are using a mobile device.');
break;
case 'Desktop':
console.log('You are using a desktop device.');
break;
case 'Tablet':
console.log('You are using a tablet device.');
break;
default:
console.log('You are using an unknown device.');
}
代码运行结果:
在上面的示例中,我们根据不同的设备类型输出不同的结果,可以根据用户的设备类型进行相应的优化。
示例代码19:使用switch语句处理不同权限
let role = 'Admin';
switch(role) {
case 'Admin':
console.log('You have admin privileges.');
break;
case 'User':
console.log('You have user privileges.');
break;
default:
console.log('You have limited privileges.');
}
代码运行结果:
在上面的示例中,我们根据用户的权限角色输出不同的结果,可以根据用户的权限角色展示不同的功能。
示例代码20:使用switch语句处理不同语言
let language = 'JavaScript';
switch(language) {
case 'JavaScript':
console.log('You are using JavaScript.');
break;
case 'Python':
console.log('You are using Python.');
break;
case 'Java':
console.log('You are using Java.');
break;
default:
console.log('You are using an unknown language.');
}
代码运行结果:
在上面的示例中,我们根据用户使用的编程语言输出不同的结果,可以根据用户的编程语言提供相应的支持和建议。
通过以上示例代码,我们详细介绍了如何使用switch语句处理不同情况,包括基本用法、多个case合并、使用break语句、不使用break语句、使用表达式、字符串、变量、逻辑运算符、处理不同类型、数组、对象、函数返回值、正则表达式、日期、用户输入、API返回值、不同浏览器、设备、权限和语言等。掌握这些用法可以让您更灵活地处理不同情况,使代码更加简洁和易读。