Web App Development

Javascript 1.7 - List comprehensions

Javascript 1.7 is specific to Firefox (2.0+). List comprehensions are not part of EcmaScript 5.1.

List comprehensions are a concise way to use map and filter on lists. Another name for them is array comprehensions.
The code below maps a list of numbers to their squares.


<script type="application/javascript; version 1.7;">
var numbers = [1, 2, 3];
var squares = [n*n for each (n in numbers)]; // parentheses around "n in numbers" are required
// squares = [1, 4, 9]
</script>

Using jQuery.map, this is equivalent to:


<script>
var numbers = [1, 2, 3];
var squares = $.map(numbers, function(n){
return n * n;
});
</script>

Using list comprehensions to filter lists

You can append an if clause to the list comprehension to filter the array:


<script type="application/javascript; version 1.7;">
var prices = [2.25, 0.95, 1.39];
var filteredPrices = ["$" + price for each (price in prices) if (price > 1.00)];
// ["$2.25", "$1.39"]
var message = "Prices over $1.00: " + filteredPrices.join(", ");
// message = "Prices over $1.00: $2.25, $1.39"
</script>

Comments


Follow me on Twitter