我正在学习JavaScript,但对以下练习感到有些困惑.我确实必须创建一个过滤器,该过滤器将接受其他功能作为排序方法.我无法理解的是for loop如何将value传递给x.你能解释一下吗?
I am learning JavaScript and got a bit confused with the following exercise. I did had to create a filter that would accept another functions as a sorting method. The thing that I cant understand a bit is how exactly the for loop passes the value to the x. Can you please explain?
function filter(arr, func) { var result = []; for (var i = 0; i < arr.length; i++) { var value = arr[i]; if (func(value)) { result.push(value); } } return result } function inBetween(a, b) { return function(x) { return a <= x && x <= b; } } function inArray(arr) { return function(x) { console.log(x) return arr.indexOf(x) != -1; } } var arr = [1, 2, 3, 4, 5, 6, 7]; alert(filter(arr, function(a) { return a % 2 == 0 })); // 2,4,6 alert( filter(arr, inBetween(3, 6)) ); // 3,4,5,6 alert( filter(arr, inArray([1, 2, 10])) ); // 1,2推荐答案
我将以这一行为例:
filter(arr, inArray([1, 2, 10])) );inArray 用arr = [1, 2, 10]调用.
对于特定的 arr ,它返回以下(匿名)函数:
It returns the following (anonymous) function, for that particular arr:
function (x) { return arr.indexOf(x) != -1; }因此原始行现在可以显示为:
So the original line now can be pictured as:
filter(arr, function (x) { return [1, 2, 10].indexOf(x) != -1; });现在调用 filter 并将 func 设置为该匿名函数.以下代码调用该函数:
Now filter is called with func set to that anonymous function. The following code calls that function:
if (func(value)) { result.push(value); }因此,当调用此 func 时,这实际上意味着调用了上述匿名函数,并且参数 x 被设置为 value 通话时刻.就像其他任何函数调用一样,该函数的参数会在实际调用中获取参数的值.
So when this func is called, this really means the above anonymous function is called, and the parameter x gets set to value at the moment of the call. It is just like with any other function call, the parameters of the function get the values of the arguments in the actual call.
更多推荐
从外部函数(数组)了解返回函数(x)
发布评论