简体   繁体   English

如何在此函数中传递参数?

[英]How are the parameters passed in this function?

Doing a text book exercise where: 做教科书练习,其中:

let arr = [1, 2, 3, 4, 5, 6, 7];

function inBetween(a, b) {
  return function(x) {
    return x >= a && x <= b;
  };
}

alert( arr.filter(inBetween(3, 6)) ); // 3,4,5,6

The textbook also states that the filter syntax to be: 教科书还指出, filter语法为:

let results = arr.filter(function(item, index, array) {
  // should return true if the item passes the filter
});

So I'm not completely understanding how the inBetween(a,b) function works... like in this line: 所以我不完全了解inBetween(a,b)函数的工作原理……像下面这样:

arr.filter(inBetween(3,6))

It seems to me like a is the item parameter, b is in the index parameter, but obviously that's not how it's working... Can someone break down this syntax and why it's working? 在我看来, aitem参数, bindex参数中,但是显然这不是它的工作原理。有人可以分解这种语法以及为什么它起作用吗?

So the filter method accepts a function that should return true or false, whether to keep the item or not. 因此,无论是否保留该项,filter方法都接受一个应返回true或false的函数。

In this example, instead of writing that function inside the filter, it's written outside and passed in. However you can still think about it like this: 在此示例中,该函数不是在过滤器内部编写,而是在外部编写并传递。但是,您仍然可以这样考虑:

let results = arr.filter(function(item, index, array) {
    return item >= 3 && item <= 6;
});

The reason you would define inBetween outside the filter is so you can pass in values instead of hard coding them into the filter like above. 之所以要在过滤器外部定义inBetween ,是因为您可以传递值,而不是像上面那样将值硬编码到过滤器中。

When you call inBetween(3,6) returned is : 当您调用inBetween(3,6)返回的是:

function(x) {
    return x >= 3 && x <= 6;
}

Like above that's then put into the filter (just without the index/array parameter since they are not needed: 像上面一样,然后将其放入过滤器中(只是不使用index/array参数,因为不需要它们:

let results = arr.filter(function(x) {
    return x >= 3 && x <= 6;
});

ab36在的范围限定inBetween和引用的返回的匿名函数,它是回调内.filter()由所指示的4castlexitem在回调函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM