CoffeeScript... 中是否省略了“do...while”循环?
在 CoffeeScript 中,while
循环是标准的:
while x()
y()
但是,以下1 不起作用:
do
y()
while x()
这只是第一个示例的糖衣:
y() while x()
CoffeeScript 是否带有内置的in 循环至少执行一次?
1顺便说一句,do
是一个关键字 - 它用于调用匿名函数。
In CoffeeScript, the while
loop comes standard:
while x()
y()
However, the following1 doesn't work:
do
y()
while x()
And this is simply sugar for the first example:
y() while x()
Does CoffeeScript come with a built-in loop that executes at least once?
1As an aside, do
is a keyword — it's used to call anonymous functions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
CoffeeScript 文档说:
我不知道至少执行一次的内置循环,所以我想替代方案是
The CoffeeScript documentation says:
I don't know of a built-in loop that executes at least once, so I guess the alternative is
我知道这个答案很旧,但自从我通过谷歌进入这里,我想其他人也可能会这样。
要在 CoffeeScript 中构建等效的 do...while 循环,我认为这种语法模拟它是最好、最简单的,并且非常易读:
I know that this answer is very old, but since I entered here via Google, I thought someone else might as well.
To construct a do...while loop equivalent in CoffeeScript I think that this syntax emulates it the best and easiest and is very readable:
您的猜测是正确的:CoffeeScript 中没有等效的
do-while
。所以你通常会写如果你发现自己经常这样做,你可以定义一个辅助函数:
Your guess is correct: There is no
do-while
equivalent in CoffeeScript. So you'd typically writeIf you find yourself doing this often, you might define a helper function:
我发现这可以通过短路条件来完成:
I found this could be accomplished through a short circuit conditional:
我一直在研究一个项目,我只是强制条件在循环结束时进行评估,然后在开始时终止。
它不是很优雅,但它确实阻止您仅为 while 代码块定义一个新函数并运行它两次。通常有一种方法可以围绕 do...while 语句进行编码,但对于那些无法做到这一点的情况,您可以有一个简单的解决方案。
I've been working on a project where I simply force the condition to evaluate at the end of the loop, then terminate at the beginning.
It's not very elegant, but it does keep you from defining a new function just for your while code block and running it twice. There generally is a way to code around the do...while statements, but for those time that you can't you have a simple solution.