过滤函数的JavaScript函数参数

Kev*_*vin 10 javascript filter

numbers = [1,2,3,4,5,4,3,2,1]; 
var filterResult = numbers.filter(function(i){
    return (i > 2);
});       
Run Code Online (Sandbox Code Playgroud)

我不明白这是如何工作的.如果我将i省略为函数参数,它会破坏函数,但是i不依赖于任何东西,为什么它需要在那里呢?

Ham*_*ish 25

.filter(Array.prototype.filter)使用3个参数调用提供的函数:

function(element, index, array) {
    ...
Run Code Online (Sandbox Code Playgroud)
  • element 是调用的特定数组元素.
  • index 是元素的当前索引
  • array 是被过滤的数组.

您可以使用任何或所有参数.

在你的情况下,i指的element是你在函数体中使用的:

function(i){
    return (i > 2);
}
Run Code Online (Sandbox Code Playgroud)

换句话说,"过滤元素element大于2".