在 CoffeeScript 中定义匿名对象数组
如何在 CoffeeScript 中定义匿名对象数组?使用 YAML 语法这是否可能?
我知道拥有一个命名对象数组非常容易:
items:[
item1:
name1:value1
item2:
name:value2
]
但是,如果这两个对象没有名称,那就有点棘手了
How do I define an array of anonymous objects in CoffeeScript? Is this possible at all, using the YAML syntax?
I know that having an array of named objects is quite easy:
items:[
item1:
name1:value1
item2:
name:value2
]
However, it would be a bit trickier, if those two objects had no names
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
简单——将一个逗号单独放置在比您定义对象的列低的列中。
将成为:
Simple -- place a comma by itself in a column lower than that in which you define your objects.
Will become:
您还可以在每个对象之间添加逗号:
You can also add a coma between each object:
你不能:
这是一些技巧:
另一个
这是最好的:
you can't:
this is some tricks:
another
this is the best:
我认为逗号解决方案更好,但我想为了完整性我应该添加这个:
I think the comma solution is better, but I figured I'd add this for completeness:
您可以在定义数组时定义变量,因此一个丑陋的答案是:
它可以工作,但您可能会收到有关“已定义但未使用的变量(item1,item2)”的警告。更好的方法是使用下划线,变量用于省略未使用的变量:
console.log JSON.stringify(a)
将产生以下结果:You can define variable while defining array, so an ugly answer would be:
It would work, but you may get warnings about "defined, but not used variables (item1, item2)". Better way would be to use underscore, variable used to omit not used variables:
console.log JSON.stringify(a)
will produce this:我很高兴地报告说,经过一番摆弄后,我可以正确编译它:
它的结果正是您所期望的:两个匿名对象的列表。
I'm very happy to report after a bit of fiddling that I could get this to compile just right:
It results it just what you'd expect: a list of two anonymous objects.
我遇到了一个相关问题并找到了这个解决方案。如果您想要一个由许多不带大括号的单个 k/v 对象组成的数组,只需缩进其中一些即可。似乎可以做到这一点。
Produces:
这对我来说是违反直觉的;您可能认为这会创建子对象,但我认为行末尾的逗号告诉它停止在该对象上创建属性。
I ran into a related problem and found this solution. If you want an array of many single k/v objects without braces, just indent some of them. Seems to do the trick.
Produces:
It's counter-intuitive to me; you'd think that this would make sub-objects but I think the comma at the end of the line tells it to stop making properties on that object.
不是OP问题的答案,但以防万一你在这里的原因和我一样......如果你的激浪很低并使用'='而不是':',那么Coffeescript将转动你的数组将对象放入平面数组中而不会出现编译错误:
生成
插入更多 Mountain Dew 并将“=”替换为“:”。
Not an answer to the OP's question, but just in case you're here for the same reason I was... If you're low on Mountain Dew and use '=' instead of ':', then Coffeescript will turn your array of objects into a flat array without a compile error:
Produces
Insert more Mountain Dew and replace the '=' with ':'.
为什么不呢:
与 js 相比,它对我来说仍然是一个巨大的改进,非常容易阅读、最小化并且编写起来非常安全。
Why not:
It's still a huge improvement to me over js, very easy to read, minimal and pretty safe to write.