javascript - 独特的数组理解

标签 javascript arrays coffeescript

我在 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/

相关文章:

javascript - 为什么 Javascript 异步/等待代码并行运行异步

javascript - Angularjs。类型错误 : Cannot read property 'apply' of undefined

python - 基于第一行合并多维 NumPy 数组

javascript - coffeescript 类中的实例变量和常量

javascript - 如何添加/删除参数以与 jquery 链接

javascript - 使用选项下拉列表过滤数据 foreach 渲染 View ,BatmanJS

javascript - 从后端强制登录 401 后使用react

javascript - "this"sequelize中的关键字不引用当前实例

javascript - 老实说很难解释..我使用a=b之类的东西,然后a++,但是b改变了。除了,这些是数组

javascript - 通过两个嵌套值过滤对象