Javascript NodeJS:重构长switch语句
我有一个很长的switch语句,我需要用更多的实践语句替换它,请提供任何帮助:Javascript NodeJS:重构长switch语句,javascript,node.js,switch-statement,Javascript,Node.js,Switch Statement,我有一个很长的switch语句,我需要用更多的实践语句替换它,请提供任何帮助: switch (global.testSuite) { case "cleanCache": testSenarios.cleanCache(); break; case "setting": testSenarios.setting(); break; case "installExtensions": testSenarios.i
switch (global.testSuite) {
case "cleanCache":
testSenarios.cleanCache();
break;
case "setting":
testSenarios.setting();
break;
case "installExtensions":
testSenarios.installExtensions();
break;
case "addIndividualContact":
testSenarios.addIndividualContact();
break;
case "addContact":
testSenarios.addContact();
break;
case "add":
testSenarios.add();
break;
}
如果testSenarios中只有有效的属性,则可以进行检查并调用带括号的函数 或者,如果您有更多属性而不是函数,则可以改为检查函数
如果testSenarios中只有有效的属性,则可以进行检查并调用带括号的函数 或者,如果您有更多属性而不是函数,则可以改为检查函数
开关盒可以很容易地替换为具有键值对的对象
//Define a object
const testSuite = {
cleanCache : testSenarios.cleanCache,
setting : testSenarios.setting
......
....
}
//Then Replace the switch-case block with a single call
testSuite[global.testSuite]()
您甚至可以添加一个“default”键来处理默认大小写。切换大小写可以很容易地替换为具有键值对的对象
//Define a object
const testSuite = {
cleanCache : testSenarios.cleanCache,
setting : testSenarios.setting
......
....
}
//Then Replace the switch-case block with a single call
testSuite[global.testSuite]()
您甚至可以添加一个“default”键来处理默认情况。testSenarios[global.testSuite]testSenarios[global.testSuite]您在设置对象时调用每个函数,而不是在替换行中调用该函数。您在设置对象时调用每个函数,然后不调用替换行中的函数。
//Define a object
const testSuite = {
cleanCache : testSenarios.cleanCache,
setting : testSenarios.setting
......
....
}
//Then Replace the switch-case block with a single call
testSuite[global.testSuite]()