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:elementis the particular array element for the call.indexis the current index of the elementarrayis the array being filtered.You can use any or all of the arguments.
In your case,
irefers to theelementand is used in the body of your function:In other words, “filter elements where
elementis greater than 2″.