【发布时间】:2021-08-26 13:59:05
【问题描述】:
上下文:我正在制作一个具有命令处理程序的游戏。在该命令处理程序中,我正在尝试优化一段代码。
我正在尝试做一个 switch-case 语句,它允许我做与下面显示的完全相同的事情
input.startsWith('echo') ? ( History.add(input), commands.echo(input) )
: ( input.startsWith('history') ? (History.add(input), commands.history(input))
: input.startsWith("new") ? (History.add(input), commands.new(input) )
: input.startsWith('theme') ? (History.add(input), commands.theme(input))
: (developerMode == true && input == "test") ? (History.add(input), commands.test())
: input.startsWith("cd") ? (History.add(input), commands.cd(input))
: input.startsWith("find") ? (History.add(input), commands.find(input, type, title))
: (History.add(input), utils.message({ user: '$', command: input }, ` - bash: ${input}: command not found `, 'error')))
简化版:
if (input.startsWith('echo')) {
History.add(input)
commands.echo(input);
} else if (input.startsWith("history"))
History.add(input)
commands.history(input);
} else if (input.startsWith("new")) {
History.add(input)
commands.new(input);
} else if (input.startsWith('theme')) {
History.add(input)
commands.theme(input);
} else if (developerMode == true && input == "test") {
History.add(input)
commands.test()
} else if (input.startsWith("cd")) {
History.add(input)
commands.cd(input)
} else if (input.startsWith("find")) {
History.add(input)
commands.find(input, type, title)
} else {
History.add(input)
utils.message({ user: '$', command: input }, ` - bash: ${input}: command not found `, 'error');
}
【问题讨论】:
-
你不想要 switch/case 语句 - if 语句本身并没有错(三元表达式版本令人厌恶!)
标签: javascript switch-statement