CoffeeScript攻略4.7:對映陣列

CoffeeScript Cookbook發表於2011-12-07

問題

你有一個物件陣列,想把這些物件對映到另一個陣列中,就像Ruby的對映一樣。

方案

使用map()和匿名函式,但不要忘了列表推導。

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 = electric_mayhem.map (muppet) -> muppet.name
# => [ 'Doctor Teeth', 'Janice', 'Sgt. Floyd Pepper', 'Zoot', 'Lips', 'Animal' ]

討論

因為CoffeeScript支援匿名函式,所以在CoffeeScript中對映陣列就像在Ruby中一樣簡單。

對映在CoffeeScript中是處理複雜轉換和連綴對映的好方法。如果你的轉換如同上例中那麼簡單,那可能將它當成列表推導看起來會清楚一些。


enter image description here

相關文章