javascript 带返回和中断的开关盒
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18393327/
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
switch-case with return and break
提问by RienNeVaPlu?s
Just out of curiosity, I often see situations like:
出于好奇,我经常看到这样的情况:
switch(something) {
case 'alice':
return something;
break;
}
Where the break
seems to be completely unnecessary, is there any reason for it to be there anyway?
凡break
似乎是完全没有必要的,没有任何理由为它在那里呢?
回答by Ja?ck
The break;
statement may have been there before the return
statement was introduced. As such, it has become redundant and can be removed.
该break;
声明可能在该return
声明被引入之前就已经存在。因此,它变得多余并且可以删除。
In fact, when you run that code through jslint, it will show this error:
实际上,当您通过jslint运行该代码时,它会显示以下错误:
Unreachable 'break' after 'return'.
“返回”后无法到达“中断”。
Whether or not to heed this advice is up to you; it could be helpful during development if you're trying out a few things before settling on a particular style.
是否听从这个建议取决于你;如果您在确定特定风格之前尝试一些事情,它可能会在开发过程中有所帮助。
This is an alternative writing style that some might argue is a better practice:
这是另一种写作风格,有些人可能会认为这是一种更好的做法:
var retval = null;
switch (something) {
case 'alice':
retval = something;
break;
// ...
}
return retval;
回答by Plato
break
tells javascript to stop evaluating cases in the switch
block. Code execution continues past the closing switch
bracket. The return
statement in the example code will indeed prevent further of anything past it, including other case
statements and anything following the switch
block.
break
告诉 javascript 停止评估switch
块中的案例。代码执行继续通过结束switch
括号。return
示例代码中的语句确实会阻止任何超出它的内容,包括其他case
语句和switch
块之后的任何内容。
I put a break
statement in every case by habit. If I wrote a case without a break
then I might copy and paste blocks of code around in the future and the lack of a break
statement would become a bug like so:
我break
习惯于在每种情况下都发表声明。如果我写了一个没有的案例,break
那么我可能会在未来复制和粘贴代码块,并且缺少break
语句会变成这样的错误:
function whereLivesA(species){
switch(species){
case 'worms':
// Relying on return to prevent further code execution within the switch
// block works but is ~bad~ smelly (according to plato :D)
var habitat = 'dirt'
return (species + ' live in ' + habitat);
case 'bees':
var habitat = 'hive';
break;
}
// Stuff to do after the switch statement (unless you returned already)
var str = species+' live in '+habitat;
return str;
}
console.log('whereLivesA');
console.log(whereLivesA("worms"));
console.log(whereLivesA("bees"));
/* Output:
whereLivesA
worms live in dirt
bees live in hive
*/
function whereLivesB(species){
switch(species){
case "worms":
// what if future code changes remove `return` and don't add `break`?
// return (species + ' live in ' + habitat)
var habitat = 'dirt';
// break;
case "bees":
var habitat = 'hive'
break;
}
// Stuff to do after the switch statement (unless you returned already)
var str = species+' live in '+habitat;
return str;
}
console.log('whereLivesB');
console.log(whereLivesB("bees"));
console.log(whereLivesB("worms"));
/* Output:
whereLivesB
bees live in hive
worms live in hive
*/
function whereLivesCorrect(species){
switch(species){
case "worms":
var habitat = 'dirt';
break;
case "bees":
var habitat = 'hive'
break;
}
// Stuff to do after the switch statement (unless you returned already)
var str = species+' live in '+habitat;
return str;
}
console.log('whereLivesCorrect');
console.log(whereLivesCorrect("bees"));
console.log(whereLivesCorrect("worms"));
/* Output:
whereLivesCorrect
bees live in hive
worms live in dirt
*/
JS newbies: If you don't want to save it to a file and run node filename
, you can press F12 and paste this script or other self contained scripts into your browser's console to run it.
JS 新手:如果你不想将它保存到文件并运行node filename
,你可以按 F12 并将此脚本或其他自包含脚本粘贴到浏览器的控制台中以运行它。
If you use node.js you can also type node
at a command line to start a node
console and paste it there.
如果您使用 node.js,您还可以node
在命令行中键入以启动node
控制台并将其粘贴到那里。
回答by matt6frey
The break
keyword is used to end the statement, or exit out of the loop so it doesn't continue running.
该break
关键字用于结束语句或退出循环的进行,因此不会继续运行。
for example:
例如:
html
html
what's your age?: <input type="text" id="ageOf"><br>
<input type="submit" onSubmit="postReply();">
<div id="reply"></div>
js
js
function postReply() {
let ageOf = document.getElementById('ageOf');
let response = document.getElementById('reply');
switch(true) {
case ageOf<18:
response.innerHTML = "Keep practicing young padewan.";
break;
case ageOf>18 && ageOf<45:
response.innerHTML = "Much too learn, you have.";
break;
case ageOf >= 45:
response.innerHTML = "You have sage wisdom.";
break;
default:
response.innerHTML = "";
break;
}
}
so on submission, the form should call the function postReply()
, check the user answer and depending on the value, it should return one of those statements.
所以在提交时,表单应该调用function postReply()
,检查用户答案,并根据值,它应该返回这些语句之一。
回答by THE AMAZING
the case is actually very necessary
这个案子其实很有必要
You have a case, then you need to break from that case or else the other cases are picked up as well.
您有一个案例,那么您需要打破该案例,否则其他案例也会被提起。
using cases is most often considered bad practice, stay away from them as much as possible.
使用案例通常被认为是不好的做法,尽可能远离它们。
switch(casein){
case 1:{
break;
}
case 2:{
break
}
}