Javascript 非法的继续声明?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14838199/
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
Illegal continue statement?
提问by Abe Miessler
I have something similar to the following code:
我有类似于以下代码的内容:
_.each data, (value, type) ->
switch type
when "answered"
icon = "results_answered"
label = definitions.results.metrics.ta
when "leftblank"
icon = "results_lb"
label = definitions.results.metrics.tlb
when "standing"
icon = "results_standing"
label = definitions.results.metrics.cs
when "minimum"
icon = "results_min"
label = definitions.results.metrics.lowest
else
continue
metricLine = utilities.div("metricline")
metricLine.grab utilities.sprite(icon, "metric_icon")
metricLine.grab utilities.div("metriclabel", label + ":")
metricLine.grab utilities.div("metricvalue", value)
metricContainer.grab(metricLine)
metricContainer
But it throws the following error to my browser:
但它向我的浏览器抛出以下错误:
Uncaught SyntaxError: Illegal continue statement
未捕获的语法错误:非法的 continue 语句
Is it possible to include a continuelike I am trying without throwing the error?
是否可以在continue不抛出错误的情况下包含我正在尝试的内容?
回答by T.J. Crowder
If you want to continue with the next loop iteration, you want return, not continue, as what you're passing to eachis a function.
如果您想继续下一个循环迭代,您需要return,而不是continue,因为您传递给的each是一个函数。
In a comment you mentioned being familiar wih the C# foreachloop, hence wanting to use continue. The difference is that wih C#'s foreach, you're dealing with an actual loop construct, whereas eachis actually calling a function for each loop iteration, so it's not (at a language level) a loop, so you can't continueit.
在您提到熟悉 C#foreach循环的评论中,因此想要使用continue. 不同之处在于,在 C# 中foreach,您正在处理实际的循环构造,而each实际上是为每次循环迭代调用一个函数,因此它不是(在语言级别)循环,因此您不能这样continue做。
回答by robkuz
you are not using a loop construct in your code but a closure. you can only exit from a loop with continue. When using underscores each function you have to exit the closure/function via return
您没有在代码中使用循环结构,而是使用闭包。您只能使用 continue 从循环中退出。使用下划线时,每个函数都必须通过 return 退出闭包/函数
#language construct
for item in items
if some_condition
continue
#closure construct
_.each data, (item) ->
if some_condition
return

