numbers = [1,2,3,4,5,4,3,2,1];
var filterResult = numbers.filter(function(i){
return (i > 2);
});
I don't understand how this works. if I omit the i as a function argument it breaks the function but the i isn't tied to anything so why does it need to be there?
.filter
(Array.prototype.filter
) calls the supplied function with 3 arguments:
function(element, index, array) {
...
element
is the particular array element for the call.index
is the current index of the elementarray
is the array being filtered.You can use any or all of the arguments.
In your case, i
refers to the element
and is used in the body of your function:
function(i){
return (i > 2);
}
In other words, "filter elements where element
is greater than 2".
i is a reference to the current object in the set when inside that closure. It could be named anything as it is just a variable, but then would have to have the same name inside the closure. Instead of using function(){}
you could use a callback which is how filter
was designed.
The reference is done implicitly by the definition of .filter
, you can read more here: http://msdn.microsoft.com/en-us/library/ff679973(v=vs.94).aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With