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

switch case中重复声明块级变量报错且无法外部调用如何解决

报错原因

  • let 声明的是块级作用域变量,整个switch语句属于同一个作用域块,你在每个case分支中都使用let重复声明同名的description变量,直接触发了块级变量重复声明的报错。
  • 即便没有声明报错,case内部用let声明的变量仅在分支内部生效,你也无法在switch语句外部访问到该变量,不符合你后续给embed设置描述的需求。

解决方案

将description的声明提前到switch语句外部,分支内仅做赋值操作即可,同时建议补充default分支避免变量未赋值的问题:

const answers = random.int(1, 5)
 
const embed = new MessageEmbed()
   .setTitle('Bank Rob')
   .setColor('GREEN')

// 提前在switch外层声明变量
let description;
switch(answers) {
  case 1:
    description = `test 1`;
    break;
  case 2:
    description = `test 2`
    break;
  case 3:
    description = `test 3`
    break;
  case 4:
    description = `test 4`
    break;
  case 5:
    description = `test 5`
    break;
  // 可选:补充默认情况兜底
  default:
    description = `default test`
}

embed.setDescription(description)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 19:54:04