Error Duplicate Const Declaration in Switch Case Statement

匿名 (未验证) 提交于 2019-12-03 01:25:01

问题:

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

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

I understand that query_url is getting declared twice which isn't right. But i don't know how to resolve this. Can someone please help on what should be the correct way to make this work?

回答1:

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; } 


回答2:

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;   } } 


回答3:

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!



回答4:

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); 


回答5:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!