具有返回和中断的开关盒

Rie*_*u͢s 21 javascript design-patterns

出于好奇,我经常看到以下情况:

switch(something) {
    case 'alice':
        return something;
    break;
}
Run Code Online (Sandbox Code Playgroud)

break看似完全没必要的地方,无论如何它有什么理由存在吗?

Ja͢*_*͢ck 25

break;声明可能已经存在了之前return介绍的语句.因此,它已经变得多余并且可以被删除.

实际上,当您通过jslint运行该代码时,它将显示以下错误:

'返回'后无法访问'休息'.

是否留意这个建议取决于你; 如果你在确定特定风格之前尝试了一些事情,它在开发过程中可能会有所帮助.

这是一种替代的写作风格,有些人可能认为这是一种更好的做法:

var retval = null;
switch (something) {
    case 'alice':
        retval = something;
        break;
    // ...
}
return retval;
Run Code Online (Sandbox Code Playgroud)


Pla*_*ato 5

break告诉javascript停止评估switch区块中的个案。代码执行将继续结束switchreturn示例代码中的语句确实将阻止进一步的执行,包括其他case语句以及该switch块之后的所有内容。

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
  */
Run Code Online (Sandbox Code Playgroud)

JS新手:如果您不想将其保存到文件中并运行node filename,则可以按F12键并将此脚本或其他自包含脚本粘贴到浏览器的控制台中以运行它。

如果使用node.js,还可以node在命令行中键入以启动node控制台并将其粘贴到那里。