lambda

Displaying 1 - 2 of 2

Python-like List Comprehensions in JavaScript

Python has a neat syntactic feature where you can take a literal list constructor's bracket notation (e.g. [2, 4, 6, 8, 10]) but have code statements generate the list's contents. So instead of writing out the 5 even numbers in the example, one could write [(x+1)*2 for x in range(5)] which turns out to be more characters but you can imagine the savings if the series in the list was longer. Instead of range() we could have a literal list [0, 1, 2, 3, 4] or even a generator function, anything which is iterable.

How could we do this...

List Comprehensions in PHP (how to emulate Python)

Python has a sweet syntactic feature where you can take a literal list written out in bracket notation (e.g. [1, 3, 5, 7, 9]) but have inline expressions generate the list's contents. So instead of writing out the 5 consecutive odd numbers like above, in Python we can say [(x*2+1 for x in range(5)] which turns out to be more characters but you can imagine the savings if the series in the list was longer and not just odd. Instead of range() we could have a literal list [0, 1, 2, 3, 4] or even a generator function, anything which is...