列表理解中的 Coffeescript assoc 数组语法
大家好:我经常遇到咖啡脚本的以下问题,想知道是否有人知道解决方案。考虑以下代码:
k=for x in [0...3]
{foo:{bar:x,baz:3},qux:5}
我有很多具有这种基本布局的代码。然而,它很难阅读。用以下方式编写此代码会更干净:
#Gives Error- PARSE ERROR ON LINE 5: UNEXPECTED 'TERMINATOR'
k=for x in [0...3]
foo:
bar:x
baz:3
qux:5
可以通过以下 hack 来避免此错误,这看起来非常难看:
k=for x in [0...3]
g=
foo:
bar:x
baz:3
qux:5
g
有谁知道在理解中使用 Coffeescript 的多行 assoc 数组语法的干净方法,而不会遇到这个错误?感谢您的帮助!
Hi everyone: I'm often running into the following issue with coffeescript and was wondering if anyone knows of a solution. Consider the following code:
k=for x in [0...3]
{foo:{bar:x,baz:3},qux:5}
I have a lot of code that has this basic layout. However, it is hard to read. It would be cleaner to write this code in the following manner:
#Gives Error- PARSE ERROR ON LINE 5: UNEXPECTED 'TERMINATOR'
k=for x in [0...3]
foo:
bar:x
baz:3
qux:5
This error can be circumvented with the following hack, which looks really ugly:
k=for x in [0...3]
g=
foo:
bar:x
baz:3
qux:5
g
Does anybody know a clean way to use Coffeescript's multi-line assoc array syntax inside of a comprehension without running into this error? Thanks for your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
因此,
无法编译,但
(例如)编译正确。我相信这是 CoffeeScript 解析器中的一个已知错误。不幸的是,还存在几个类似的问题,因为解析 YAML 样式的对象变得异常棘手。所以现在,我将使用显式花括号,正如 c3rin 所建议的那样。
[编辑:具体请参阅问题 981。]
So,
fails to compile, but
(for instance) compiles correctly. I believe this is a known bug in the CoffeeScript parser. Unfortunately, there are several similar issues open, as parsing YAML-style objects has turned out to be exceptionally tricky. So for now, I'd use explicit curly braces, as c3rin suggests.
[Edit: See issue 981 specifically.]
.map()
是你的朋友:(我知道你的问题实际上是一个错误,但这在我看来更有意义。列表推导更适合简单的任务)
.map()
is your friend here:(i know your problem is actually a bug, but this makes more sense IMO. list comprehensions are better suited to simple tasks)
我已经改变了我的答案几次,但我认为你的第一个例子的问题是咖啡脚本编译器认为 foo: 是你想要构建的对象,并且当它到达 qux: 时会担心,因为它认为它是一个不同的对象完全是 object 而不是 foo。有趣的是,您可以混合 JSON 样式和 YAML 样式声明,使用 JSON 样式花括号显式声明对象定义的边界,并在边界内部使用 YAML 以提高可读性。
I've changed my answer a couple of times, but I think the issue with your first example is that coffeescript compiler thinks that foo: is the object you want to build and is concerned when it gets to qux: because it thinks its a different object altogether than foo. What's interesting is that you can mix the JSON-style and YAML-style declarations, using the JSON-style curly braces to explicitly declare the boundaries of the object definition, and the use YAML inside of the boundaries for readability.
我通常的解决方案如下:
设置变量返回其设置的值。它仍然有点 hacky,但比设置后显式返回
g
的版本稍微好一些。不过,这绝对是咖啡脚本错误的解决方法。My usual solution for this is the following:
Setting a variable returns the value it is set to. Its still a bit hacky, but slightly nicer than your version that explicitly returns
g
after setting it. Definitely a workaround for a coffeescript bug, though.