简体   繁体   English

带返回和中断的开关盒

[英]switch-case with return and break

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似乎完全没有必要的地方,有什么理由让它在那里吗?

The break; break; statement may have been there before the return statement was introduced.语句可能在引入return语句之前就已经存在。 As such, it has become redundant and can be removed.因此,它变得多余并且可以删除。

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;

break tells javascript to stop evaluating cases in the switch block. break告诉 javascript 停止评估switch块中的情况。 Code execution continues past the closing switch bracket.代码执行继续通过关闭switch括号。 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.示例代码中的return语句确实会阻止任何超出它的内容,包括其他case语句和switch块之后的任何内容。

I put a break statement in every case by habit.我习惯于在每种情况下放置一个break语句。 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语句将成为这样的错误:

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控制台并将其粘贴到那里。

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() ,检查用户的答案,并根据值,它应该返回这些语句之一。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM