【问题标题】:Redeclaring variables in switch case在 switch case 中重新声明变量
【发布时间】:2021-12-05 10:13:35
【问题描述】:
const answers = random.int(1, 5)
 
const embed = new MessageEmbed()
   .setTitle('Bank Rob')
   .setColor('GREEN')
    
   switch(answers) {
     case 1:
       let description = `test 1`;
       break;
     case 2:
       let description = `test 2`
       break;
     case 3:
       let description = `test 3`
       break;
     case 4:
       let description = `test 4`
       break;
     case 5:
       let description = `test 5`
       break;
   }

embed.setDescription(description)

我正在尝试分配变量 description 以在 switch case 语句之外使用,但出现错误:

Cannot redeclare block-scoped variable "description"

【问题讨论】:

  • let description移到switch之外?
  • 这绝对应该被标记为重复,但我实际上找不到处理这个用例的答案。
  • 它不起作用的主要原因是let 语句将尝试在switch 语句中初始化变量。你应该在switch开始之前初始化它,然后赋值。

标签: typescript discord.js


【解决方案1】:

解决这个问题的最简单方法是完全避免switch:将描述放在一个数组中并对其进行索引。

const DESCRIPTIONS = ['test 1', 'test 2', 'test 3', 'test 4', 'test 5'];
const answers = random.int(1, 5)
 
const embed = new MessageEmbed()
   .setTitle('Bank Rob')
   .setColor('GREEN')

embed.setDescription(DESCRIPTIONS[answers - 1]); // array is indexed from 0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-27
    • 2010-11-16
    • 2016-06-15
    • 2015-08-02
    • 2021-12-13
    • 1970-01-01
    • 2013-05-15
    相关资源
    最近更新 更多