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 \'
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;
})()
];