如何在 Coffeescript 中实现 array.any() 和 array.all() 方法?
如何在 Coffeescript 中实现 array.any() 和 array.all() 方法?
How to implement array.any()
and array.all()
methods in Coffeescript?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这些实际上是 Javascript 1.6 的一部分,并且在 CoffeeScript 中的工作方式相同。您需要 some 和 每。
不知道你是什么环境,但是IE< 9 似乎不支持这些方法。它们很容易添加。这些页面上有一段代码向您显示兼容性代码,如果您愿意,您可以将它们转换为 CoffeeScript,尽管您 不必。
一种更粗略、更简单的方法是(未经测试):
但这两种方法都没有短路逻辑。 编辑:但请参阅里卡多的答案以获得更好的版本。
Those are actually part of Javascript 1.6 and will work just the same in CoffeeScript. You want some and every.
I don't know what environment you're in, but IE < 9 doesn't seem to support those methods. They're pretty easy to add. There's a snippet of code on those pages that show you compatibility code and if you want you can translate them to CoffeeScript, though you don't have to.
A cruder, simpler way would be (untested):
But neither of those have short circuit logic. Edit: But see Ricardo's answer for a better version of them.
短路(优化)版本:
?=
用于“存在赋值”,仅在该属性为null
/undefined
时运行。Short-circuited (optimized) versions:
The
?=
is for "existential assignment", only runs when that property isnull
/undefined
.查看 underscore.js,它为您提供了
_.any
和 < code>_.all 方法(又名_.some
和_.every
)将在任何主要 JS 环境中运行。以下是它们在 underscore.coffee 中的 CoffeeScript 中的实现方式:(这些依赖于
_.each
,这是一种简单的迭代方法,以及_.breakLoop
,它只是抛出异常。)Check out underscore.js, which provides you with
_.any
and_.all
methods (a.k.a._.some
and_.every
) that will run in any major JS environment. Here's how they're implemented in CoffeeScript in underscore.coffee:(These depend on
_.each
, which is a straightforward iteration method, and_.breakLoop
, which just throws an exception.)我今天正在研究这个,并决定将
all
实现为折叠,我想您也可以对any
执行相同的操作(但它不会短路,要么):非短路
any
大多相似:我这样做是因为我发现它是可读的。另外,我只是将其作为自由浮动函数而不是数组方法来实现。
I was looking at this today and decided to implement
all
as a fold, and I suppose you could do the same forany
as well (but it doesn't short circuit, either):The non-short-circuiting
any
would be mostly similar:I did
all
this way because I found it to be readable. Also, I just did it as a free-floating function instead of an array method.