types.Array.map
Builds a new array from the results of callback on each element.
... from the prose below, not from the signature.Parameters
callback | function | callback(value, [index], [array]), called for each element, in order |
Return value
A new array, one result per source element that was not dropped (see Notes).
Errors
Whatever callback throws, on the first element where it throws, except a thrown null (see Notes).
Notes
callback gets exactly as many of the arguments listed above as it declares parameters for, and never more.
callback may throw null to drop that element instead of contributing to the result, so a filter and a map that can share one pass over the array can be written as one map instead of filter followed by map. This is specific to map: none of the other array iteration methods (each, filter, apply, findindex, findvalue, reduce) give a thrown null any special meaning; there, it aborts like any other thrown value.
Example
let a = [1, 2, 3, 4];
let squares = a.map(function(v) { return v * v });
println("squares =", ", ".join(squares.map(@(v) v.tostring())));
println("squares == a:", squares == a); // map() always returns a new array
// throwing null inside the callback drops that element instead of failing
let odds = a.map(function(v) { if (v % 2 == 0) throw null; return v });
println("odds =", ", ".join(odds.map(@(v) v.tostring())));squares = 1, 4, 9, 16
squares == a: false
odds = 1, 3See also
apply | Replaces every element with the result of callback on it. |
filter | Collects the elements for which callback returns a true value. |
| array | class index |