Reputation: 95
I am fairly new to js and I have been looking at the Mozilla Developer site. Under the functions section, I can't seem to grasp the following
function map(f,a) {
var result = [], // Create a new Array
i;
for (i = 0; i != a.length; i++)
result[i] = f(a[i]);
return result;
}
particulary, this line "result[i] = f(a[i]);"
From Mozilla: Function expressions are convenient when passing a function as an argument to another function. The following example shows a map function being defined and then called with an anonymous function as its first parameter
Can you help explain this?
Here is a link for reference. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions
Upvotes: -1
Views: 67
Reputation: 686
result[i] = f(a[i]);
result is an array and the element at index i is being assigned the result of a function call which takes the parameter a[i].
f in the line above is an anonymous function which is parsed into the map function as the first argument. f would be defined somewhere else in code with the following syntax
function(value) {
return result.
}
The calling code of your example above would look something like.
var array = map(function(value) { return result; },[1,2,3,4,5]);
I would read up on anonymous functions here which might help. http://en.wikibooks.org/wiki/JavaScript/Anonymous_Functions
Upvotes: -1
Reputation: 24531
this piece of code applies to every element of array "a" function "f" and returns the array "result" which contains the results of running function "f" for every element in "a".
Sorry, I've got a recursion :)
Actually it can be used like that:
var array = map(function(val){ return val + 1; },[1,2,3,4,5]);
and in "array" you will have these values:
[2,3,4,5,6]
Upvotes: 0