Javascript Switch Case 语句中的重复常量声明错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35746371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error Duplicate Const Declaration in Switch Case Statement
提问by asanas
I have the following code and I get the error 'Duplicate Declaration query_url'.
我有以下代码,但收到错误“重复声明 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?
我知道 query_url 被声明了两次,这是不对的。但我不知道如何解决这个问题。有人可以帮助了解进行这项工作的正确方法吗?
采纳答案by eltonkamami
if query_url
can have multiple values depending on the switch branch obviously you need a variable ( declare either with var
or let
).
ifquery_url
可以根据 switch 分支有多个值,显然你需要一个变量(声明 withvar
或let
)。
const is set once and stays that way.
const 设置一次并保持这种状态。
example usage with let
let 的示例用法
let query_url = '';
switch(condition) {
case 'complex':
query_url = `something`;
break;
default:
query_url = `something`;
break;
}
回答by Bergi
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;
}
}
回答by rob2d
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)
(这需要 ES6 或在 Node 4.x 中声明“use-strict”)
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!
当然,也取决于嵌入在这些 switch 语句中的外部逻辑的数量!
回答by Zakaria
Just put your switch
in a function with some return statements :
只需将您switch
的函数放入带有一些返回语句的函数中:
var condition;
function aSwitch(condition){
switch(condition) {
case 'complex':
return 'something';
default:
return 'something';
}
}
const query_url = aSwitch(condition);
回答by sbk201
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.
缺点是,你不能有对象的默认值,你需要额外检查条件。