You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript游戏命令处理优化:如何用switch case实现startsWith的if分支等价逻辑

命令处理器switch-case实现方案

以下实现与你提供的三目运算、if-else版本逻辑完全一致,同时将所有分支共有的历史记录插入逻辑提取到switch外部,减少重复代码,无功能变更:

// 所有场景均会执行历史记录插入,提前避免重复调用
History.add(input)

switch (true) {
  case input.startsWith('echo'):
    commands.echo(input)
    break
  case input.startsWith('history'):
    commands.history(input)
    break
  case input.startsWith('new'):
    commands.new(input)
    break
  case input.startsWith('theme'):
    commands.theme(input)
    break
  case developerMode === true && input === 'test':
    commands.test()
    break
  case input.startsWith('cd'):
    commands.cd(input)
    break
  case input.startsWith('find'):
    commands.find(input, type, title)
    break
  default:
    utils.message({ user: '$', command: input }, ` - bash: ${input}: command not found `, 'error')
}

如果你需要完全保留每个分支内单独调用History.add(input)的写法(和原代码结构完全对齐,无逻辑优化),可以使用如下版本:

switch (true) {
  case input.startsWith('echo'):
    History.add(input)
    commands.echo(input)
    break
  case input.startsWith('history'):
    History.add(input)
    commands.history(input)
    break
  case input.startsWith('new'):
    History.add(input)
    commands.new(input)
    break
  case input.startsWith('theme'):
    History.add(input)
    commands.theme(input)
    break
  case developerMode === true && input === 'test':
    History.add(input)
    commands.test()
    break
  case input.startsWith('cd'):
    History.add(input)
    commands.cd(input)
    break
  case input.startsWith('find'):
    History.add(input)
    commands.find(input, type, title)
    break
  default:
    History.add(input)
    utils.message({ user: '$', command: input }, ` - bash: ${input}: command not found `, 'error')
}

内容的提问来源于stack exchange,提问作者Nullify

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 09:15:03