代码之家  ›  专栏  ›  技术社区  ›  james

该函数中的参数是如何传递的?

  •  1
  • james  · 技术社区  · 8 年前

    做一个课本练习,其中:

    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
    

    教科书还指出 filter 语法为:

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

    所以我不完全理解 inBetween(a,b) 函数工作。。。就像这一行:

    arr.filter(inBetween(3,6))
    

    在我看来 a item 参数 b index 参数,但显然这不是它的工作方式。。。有人能分解这个语法吗?为什么它能工作?

    2 回复  |  直到 8 年前
        1
  •  2
  •   castletheperson    8 年前

    因此filter方法接受一个函数,该函数应返回true或false,无论是否保留该项。

    在本例中,不是在过滤器内编写该函数,而是在外部编写并传入。然而,你仍然可以这样想:

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

    您将定义的原因 inBetween 过滤器外部是这样,您可以传入值,而不是像上面那样将它们硬编码到过滤器中。

    当你打电话的时候 inBetween(3,6) 返回的是:

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

    如上所述,然后将其放入过滤器(只是没有 index/array 参数,因为它们不需要:

    let results = arr.filter(function(x) {
        return x >= 3 && x <= 6;
    });
    
        2
  •  0
  •   guest271314    8 年前

    a b , 3 , 6 定义在 inBetween 并在返回的匿名函数中引用,该函数是 .filter() ,如所示 4castle , x item 在回调函数处