我在 CoffeeScript 中有以下数组:
electric_mayhem = [ { name: "Doctor Teeth", instrument: "piano" },
{ name: "Janice", instrument: "piano" },
{ name: "Sgt. Floyd Pepper", instrument: "bass" },
{ name: "Zoot", instrument: "sax" },
{ name: "Lips", instrument: "bass" },
{ name: "Animal", instrument: "drums" } ]
我的目标是从该数组中获取所有乐器名称。
预期结果:['钢琴'、'贝斯'、'萨克斯'、'鼓']
我的第一个解决方案基于 this :
names = (muppet.instrument for muppet in electric_mayhem)
output = {}
output[name] = name for name in names
names = (value for key, value of output)
这相当长。我查看了转译后的 JavaScript,发现第一行被翻译为:
names = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = electric_mayhem.length; _i < _len; _i++) {
muppet = electric_mayhem[_i];
_results.push(muppet.instrument);
}
return _results;
})();
因此,我编写了一个 super hacky 解决方案,它使用在转译过程中引入的 _results
变量:
names = (muppet.instrument for muppet in electric_mayhem \
when muppet.instrument not in _results)
它可以工作,但我不喜欢它依赖于未记录的变量名称,因此它可能会在未来版本的 CoffeeScript 中出现问题。
是否有任何一句话可以以非 hacky 的方式实现“独特的理解”?
最佳答案
这句话可能会起作用:
names = (key for key of (new -> @[o.instrument] = '' for o in electric_mayhem; @))
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// "object comprehension"
作为您自己,我(ab)使用了关联数组来将其键用作唯一值集。
但是,这里真正的技巧是使用“对象理解”来构建该数组。或者至少是 CoffeeScript 目前提供的最接近的等效形式:
(new -> @[o.instrument] = '' for o in electric_mayhem; @)
// ^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^
// create with |
// a new that |
// empty anonymous |
// object constructor |
// don't forget -/
// to return the
// newly created object
关于javascript - 独特的数组理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25260425/