在 Coffeescript 中连接数组的数组
我试图在 Coffeescript 中找到一种优雅的方式来合并数组数组,以便 [[1,2,3],[4,5,6],[7,8,9]] ==> [1,2,3,4,5,6,7,8,9]。
正如您可能想象的那样,我需要这个,因为我正在从“for in”构造中的函数生成数组,并且需要连接生成的嵌套数组:
结果=(为arr中的x生成_array(x))
有没有一种优雅的方法来处理这个问题?感谢您的指点!
I'm trying to find an elegant way in Coffeescript to merge an array of arrays, so that [[1,2,3],[4,5,6],[7,8,9]] ==> [1,2,3,4,5,6,7,8,9].
As you might imagine, I need this because I'm generating arrays from a function in a "for in" construct and need to concatenate the resulting nested array:
result = (generate_array(x) for x in arr)
Is there an elegant way to handle this? Thanks for any pointers!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
只需使用 JS 习惯用法:
这在 Coffee 中会变得更好一点:
Just use the JS idiom:
which becomes a little nicer in Coffee:
好的,一种方法是包含 underscore.js 库。它是一个非常好的、轻量级但功能强大的实用程序库,并且它有 _.flatten 正是这样做的。
除此之外,您可以采用 underscore.js 代码进行展平并修改它以删除任何其他下划线依赖项,以创建您自己的独立“展平”。
这是 underscore.js “_.flatten” 代码:
请注意,它正在为您做一些不错的事情。例如,许多下划线函数(如 _.reduce)将检查浏览器是否已实现本机版本(有些浏览器已经实现)。如果是这样,它将使用本机,当然运行速度要快得多。 _.isArray 实现做了同样的事情。
OK, one way is to include the underscore.js library. It is a very nice, lightweight but powerful utility library, and it has _.flatten which does exactly this.
Barring that, you could take the underscore.js code for flatten and modify it to remove any other underscore dependencies to create your own standalone "flatten".
Here's the underscore.js "_.flatten" code:
Notice that it is doing some nice stuff for you. For example, many of the underscore functions like _.reduce will check to see if the browser has implemented a native version, which some have. If so, it will use the native which of course runs much faster. The _.isArray implementation does the same thing.
对于 Coffee 来说这个怎么样
,或者对于纯 Javascript 来说怎么样?
What about this for Coffee
or this for pure Javascript
Sugarjs 是另一种优雅的方式:
sugarjs: flatten
sugarjs is another elegance way to do it:
sugarjs: flatten
为什么不尝试使用 Lodash?
https://lodash.com/docs#flatten
Why not try using Lodash?
https://lodash.com/docs#flatten