Kan*_*ter 3 javascript switch-statement
我的代码不是很长,所以我把它全部粘贴在这里。
代码不完整,但是当我运行它时,它首先跳转到它应该的 case“start”,然后跳转到 case“end”。我可以看到它,因为它打印了两个块的控制台日志文本。为什么会跳到“结束”的情况下?
<html>
<body>
<script>
function stepStream(stream,step){
switch (stream[step]){
case "start":
console.log("Started reading stream...");
case "end":
var success = "Finished reading dataStream.";
console.log(success);
return success;
default:
throw "Data stream format is bad";
case "gesture":
console.log("Running case gesture! But why?");
step+=1;
stepStream(stream,step);
case "say":
step+=1;
stepStream(stream,step);
case "sleep":
step+=1;
stepStream(stream,step);
}
}
var sentence1 = "Where are my bananas? I thought you put them in my bag?";
var sentence2 = "This is a rather irritating situattion.";
var dataStream = ["start","gesture","banzai","sleep",1.0,"say",sentence1,
"say",sentence2,"gesture","kubikasige","end"];
stepStream(dataStream,0);//Second parameter sets where to start reading the dataStream.
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
问题是您break
在case
代码之后缺少关键字。没有中断,后续块将被执行,这就是为什么end
在start
代码之后执行。您可以在此 W3Schools 链接上阅读有关此内容的更多信息。
此外,来自JS 参考:
与每个 case 标签相关联的可选 break 语句确保程序在执行匹配的语句后中断 switch 并在 switch 之后的语句处继续执行。如果省略 break ,程序将在 switch 语句中的下一个语句继续执行。
所以你的代码应该是这样的:
function stepStream(stream,step){
switch (stream[step]){
case "start":
console.log("Started reading stream...");
break;
case "end":
var success = "Finished reading dataStream.";
console.log(success);
return success;
default:
throw "Data stream format is bad";
case "gesture":
//commUGesture(stream[i+1]);
//createLogLine("robot:CommU","event:gesture:"+stream[i+1]);
console.log("Running case gesture! But why?");
step+=1;
stepStream(stream,step);
break;
case "say":
step+=1;
stepStream(stream,step);
break;
case "sleep":
step+=1;
stepStream(stream,step);
break;
}
Run Code Online (Sandbox Code Playgroud)
您的“结束”案例在最后有一个回报,因此代码不会落入其他案例。理想情况下,break
每个末尾都应该有一个。