Make Javascript do List Comprehension

后端 未结 10 1178
情话喂你
情话喂你 2020-12-05 09:05

What is the cleanest way to make Javascript do something like Python\'s list comprehension?

In Python if I have a list of objects whose name\'s I want to \'

10条回答
  •  自闭症患者
    2020-12-05 09:44

    Those interested in "beautiful" Javascript should probably check out CoffeeScript, a language which compiles to Javascript. It essentially exists because Javascript is missing things like list comprehension.

    In particular, Coffeescript's list comprehension is even more flexible than Python's. See the list comprehension docs here.

    For instance this code would result in an array of name attributes of input elements.

    [$(inp).attr('name') for inp in $('input')]
    

    A potential downside however is the resulting Javascript is verbose (and IMHO confusing):

    var inp;
    [
      (function() {
        var _i, _len, _ref, _results;
        _ref = $('input');
        _results = [];
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          inp = _ref[_i];
          _results.push($(inp).attr('name'));
        }
        return _results;
      })()
    ];
    

提交回复
热议问题