gpt4 book ai didi

coffeescript - CoffeeScript 中的 While 循环

转载 作者:行者123 更新时间:2023-12-01 11:46:17 24 4
gpt4 key购买 nike

我是 CoffeeScript 的新手,一直在阅读这本书,The Little Book on CoffeeScript .以下是本书第 2 章中让我在阅读时感到困惑的几行:

The only low-level loop that CoffeeScript exposes is the while loop. This has similar behavior to the while loop in pure JavaScript, but has the added advantage that it returns an array of results, i.e. like the Array.prototype.map() function.

num = 6
minstrel = while num -= 1
num + " Brave Sir Robin ran away"

虽然它对于 CoffeeScript 程序员来说可能看起来不错,但作为新手,我无法理解代码的作用。此外,返回结果数组这句话似乎与 while 是循环结构而不是函数的事实不符。因此,它返回 某些内容的概念似乎令人困惑。此外,在循环的每次迭代中,带有字符串 "Brave Sir Robin ran away" 的变量 num 似乎很尴尬,因为值 num 被用作循环计数器。

如果您能解释代码的行为,并可能通过更简单的示例说明作者试图传达的内容,我将不胜感激。

最佳答案

哇!我不知道,但如果您记得 Coffeescript 总是返回“ block ”的最后一个表达式,那绝对有意义。因此,在您的情况下,它返回(如果这让您感到困惑,则不是通过“return”语句)表达式

 num + " Brave Sir Robin ran away" 

从与 while 条件关联的 block 中,因为您将返回多个这样的表达式,所以它将它们压入一个数组。

查看生成的 JavaScript,它可能会更清楚,因为生成的代码几乎是过程性的

var minstrel, num;

num = 6;

minstrel = (function() {
var _results;
_results = [];
while (num -= 1) {
_results.push(num + " Brave Sir Robin ran away");
}
return _results;
})();

我希望这对你有意义。

关于coffeescript - CoffeeScript 中的 While 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14973396/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com