CoffeeScript 列表推导

列表推导

问题

你有一个对象数组,想将它们映射到另一个数组,类似于Python的列表推导。

解决方案

使用列表推导,但不要忘记还有[mapping-arrays]( http://coffeescript-cookbook.github.io/chapters/arrays/mapping-arrays) 。

electric_mayhem = [ { name: "Doctor Teeth", instrument: "piano" },
                    { name: "Janice", instrument: "lead guitar" },
                    { name: "Sgt. Floyd Pepper", instrument: "bass" },
                    { name: "Zoot", instrument: "sax" },
                    { name: "Lips", instrument: "trumpet" },
                    { name: "Animal", instrument: "drums" } ]

names = (muppet.name for muppet in electric_mayhem)
# => [ Doctor Teeth, Janice, Sgt. Floyd Pepper, Zoot, Lips, Animal ]

讨论

因为CoffeeScript直接支持列表推导,在你使用一个Python的语句时,他们会很好地起到作用。对于简单的映射,列表推导具有更好的可读性。但是对于复杂的转换或链式映射,映射数组可能更合适。

作者:冒牌SEO,如若转载,请注明出处:https://www.web176.com/coffeescript/10672.html

(0)
打赏 支付宝 支付宝 微信 微信
冒牌SEO冒牌SEO
上一篇 2023年2月26日
下一篇 2023年2月26日

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注