Error Duplicate Const Declaration in Switch Case Statement

前端 未结 6 1626
别跟我提以往
别跟我提以往 2020-11-27 05:07

I have the following code and I get the error \'Duplicate Declaration query_url\'.

  switch(condition) {
    case \'complex\':
      const query_url = `somet         


        
相关标签:
6条回答
  • 2020-11-27 05:32

    Try wrapping the cases in blocks:

    switch(condition) {
      case 'complex': {
        const query_url = `something`;
        … // do something
        break;
      }
      default: {
        const query_url = `something`;
        … // do something else
        break;
      }
    }
    
    0 讨论(0)
  • 2020-11-27 05:40

    if you need to redeclare the same variable in each case see @Bergi 's answer bellow

    if query_url can have multiple values depending on the switch branch obviously you need a variable ( declare either with var or let ).

    const is set once and stays that way.

    example usage with let

    let query_url = '';
    switch(condition) {
      case 'complex':
        query_url = `something`;
        break;
      default:
        query_url = `something`;
        break;
    }
    
    0 讨论(0)
  • 2020-11-27 05:46
    const query_url={
      complex:'something complex',
      other:'other thing'
    }[condition]
    

    The drawback is,you can't have default with object,you need to have addition check of condition.

    0 讨论(0)
  • 2020-11-27 05:46

    You can use {} to scope your switch case.

    For your case you need to return the variable as long as the var exists and is accessible between curly braces :

     switch(condition) {
        case 'complex': {
          const query_url = `something`;
          return query_url;
        }
        default: {
          const query_url = `something`;
          return query_url;
        }
      }
    

    If you wont use return you must declare a let query_url above your switch statement.

    0 讨论(0)
  • 2020-11-27 05:47

    I personally prefer (and tend to abuse) the following in these sorts of cases:

    const query_url = (()=>
    {
         switch(condition)
               case 'complex': return 'something';
               default       : return 'something-else';
    })();
    

    (this requires ES6 or declaring "use-strict" in Node 4.x though)

    Update: Alternatively, much more compact depending on if there is any logic there or if it's a simple assignment:

    const query_url = {complex : 'something'}[condition] || 'something-else';
    

    Also, of course, depends on the amount of outside-logic embedded in those switch statements!

    0 讨论(0)
  • 2020-11-27 05:49

    Just put your switch in a function with some return statements :

    var condition;
    function aSwitch(condition){
    switch(condition) {
        case 'complex':
          return 'something';
        default:
          return 'something';
      }
    }
    const query_url = aSwitch(condition);
    
    0 讨论(0)
提交回复
热议问题