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 \'
A list comprehension has a few parts to it.
In JavaScript, as of ES5 (so I think that's supported in IE9+, Chrome and FF) you can use the map and filter functions on an array.
You can do this with map and filter:
var list = [1,2,3,4,5].filter(function(x){ return x < 4; })
.map(function(x) { return 'foo ' + x; });
console.log(list); //["foo 1", "foo 2", "foo 3"]
That's about as good as it's going to get without setting up additional methods or using another framework.
As for the specific question...
With jQuery:
$('input').map(function(i, x) { return x.name; });
Without jQuery:
var inputs = [].slice.call(document.getElementsByTagName('input'), 0),
names = inputs.map(function(x) { return x.name; });
[].slice.call() is just to convert the NodeList to an Array.