JavaScript中switch的四种写法示例

JavaScript中switch的四种写法示例

JavaScript中的switch语句用于对某个变量进行多分支判断,根据变量的值执行相应的代码块。本文将介绍JavaScript中switch语句的四种不同写法,包括常规写法、函数式写法、对象字面量写法和Map写法。

1. 常规写法

switch语句的常规写法如下:

switch(expression) {

case value1:

statement1;

break;

case value2:

statement2;

break;

...

default:

statement;

}

其中,expression是要进行判断的表达式,value1、value2等则是表达式可能的返回值,对应的statement1、statement2等则是相应的代码块。default是可选的,代表当expression没有匹配到任何一个case时执行的代码块。

下面是一个常规写法的示例:

const fruit = 'apple';

switch (fruit) {

case 'banana':

console.log('This is a banana.');

break;

case 'orange':

console.log('This is an orange.');

break;

case 'apple':

console.log('This is an apple.');

break;

default:

console.log('This is not a fruit.');

}

// Output: This is an apple.

上面的代码中,fruit变量的值是'apple',因此对应的case 'apple'代码块被执行,输出'This is an apple.'。

2. 函数式写法

函数式写法是将每个case语句的代码块封装成函数,然后在switch语句中调用相应的函数。这样可以使代码更加简洁和易于维护。

下面是一个函数式写法的示例:

const fruit = 'apple';

function banana() {

console.log('This is a banana.');

}

function orange() {

console.log('This is an orange.');

}

function apple() {

console.log('This is an apple.');

}

switch (fruit) {

case 'banana':

banana();

break;

case 'orange':

orange();

break;

case 'apple':

apple();

break;

default:

console.log('This is not a fruit.');

}

// Output: This is an apple.

上面的代码中,三个函数banana()、orange()和apple()分别对应switch语句中的三个case语句。fruit变量的值是'apple',因此对应的apple()函数被执行,输出'This is an apple.'。

3. 对象字面量写法

对象字面量写法是将case语句的代码块封装成一个对象,然后在switch语句中调用相应的属性。这种写法不仅简洁易读,还可以使代码更加灵活,因为可以动态修改对象的属性,而不需要改变switch语句本身。

下面是一个对象字面量写法的示例:

const fruit = 'apple';

const fruits = {

banana: () => console.log('This is a banana.'),

orange: () => console.log('This is an orange.'),

apple: () => console.log('This is an apple.'),

default: () => console.log('This is not a fruit.')

}

if (fruits[fruit]) {

fruits[fruit]();

} else {

fruits.default();

}

// Output: This is an apple.

上面的代码中,fruits对象定义了四个属性,对应着switch语句中的四个case语句。如果fruit变量值对应着fruits对象中的一个属性,则调用相应的函数;否则,调用default属性对应的函数。fruit变量的值是'apple',因此对应的apple()函数被执行,输出'This is an apple.'。

4. Map写法

Map写法是将case语句的代码块封装成一个Map对象,然后在switch语句中调用相应的函数。与对象字面量写法类似,这种写法可以使代码更加简洁和灵活。

下面是一个Map写法的示例:

const fruit = 'apple';

const fruits = new Map([

['banana', () => console.log('This is a banana.')],

['orange', () => console.log('This is an orange.')],

['apple', () => console.log('This is an apple.')]

])

if (fruits.has(fruit)) {

fruits.get(fruit)();

} else {

console.log('This is not a fruit.');

}

// Output: This is an apple.

上面的代码中,fruits对象是一个Map对象,它的键值对分别对应着switch语句中的三个case语句。如果fruit变量值对应着fruits对象中的一个键,调用相应的函数;否则,输出'This is not a fruit.'。fruit变量的值是'apple',因此对应的apple()函数被执行,输出'This is an apple.'。

总结

本文介绍了JavaScript中switch语句的四种不同写法,包括常规写法、函数式写法、对象字面量写法和Map写法。这些写法各有优缺点,开发者可以根据实际需求选择一种合适的写法。

免责声明:本文来自互联网,本站所有信息(包括但不限于文字、视频、音频、数据及图表),不保证该信息的准确性、真实性、完整性、有效性、及时性、原创性等,版权归属于原作者,如无意侵犯媒体或个人知识产权,请来电或致函告之,本站将在第一时间处理。撸码网站发布此文目的在于促进信息交流,此文观点与本站立场无关,不承担任何责任。