【问题标题】:Filter with CoffeeScript list comprehensions使用 CoffeeScript 列表推导过滤
【发布时间】:2011-06-17 21:51:20
【问题描述】:

CoffeeScript 文档指出列表推导应该能够执行选择/过滤操作:

他们应该能够处理大多数 否则你会使用的地方 循环、每个/forEach、映射或 选择/过滤。

你会想象你可以在一行中做一些事情,比如result = item for item in list if item % 2 == 0 但是我能来的最接近的是

list = [1,2,3,4]
result = []
for item in list
  if item % 2 == 0 then result.push item

在 CoffeeScript 中过滤列表最简洁的方法是什么?

【问题讨论】:

    标签: list-comprehension coffeescript


    【解决方案1】:
    result = (item for item in list when item % 2 == 0)
    

    编辑:添加result =

    【讨论】:

    【解决方案2】:

    除非你试图挤出每一盎司的性能,否则我会创建一个这样的过滤函数:

    filter = (list, func) -> x for x in list when func(x)
    

    或者如果你想将它添加到每个数组的原型中:

    Array::filter = (func) -> x for x in @ when func(x)
    

    然后写:(分别)

    result = filter mylist, (x) -> x % 2 == 0
    

    result = mylist.filter (x) -> x % 2 == 0
    

    作为参考,这是生成的 javascript:

    var filter, result;
    filter = function(list, func) {
        var x, _i, _len, _results;
        _results = [];
        for (_i = 0, _len = list.length; _i < _len; _i++) {
            x = list[_i];
            if (func(x)) {
                _results.push(x);
            }
        }
        return _results;
    };
    Array.prototype.filter = function(func) {
        var x, _i, _len, _results;
        _results = [];
        for (_i = 0, _len = this.length; _i < _len; _i++) {
            x = this[_i];
            if (func(x)) {
                _results.push(x);
            }
        }
        return _results;
    };
    result = filter(mylist, function(x) {
        return x % 2 === 0;
    });
    result = mylist.filter(function(x) {
        return x % 2 === 0;
    });
    

    有一个类似的问题here

    【讨论】:

    • 这绝对是个人喜好问题,因为它们都能完成工作 - 但以 python 为例,列表推导通常比函数式编程函数更受欢迎,因为它们被认为更具可读性。跨度>
    • 笏。 Array 已经有了这个确切的功能……(只是可能更有效)
    猜你喜欢
    • 2022-01-13
    • 1970-01-01
    • 2017-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-27
    • 2012-07-15
    • 1970-01-01
    相关资源
    最近更新 更多