使用闭包的乘法选择的数组过滤器功能-Javascript

Rob*_*yan 4 javascript arrays closures filter

我需要为过滤器创建一个函数,它必须有2个选择。

  1. inBetween(a, b)-这将返回a和之间的数组b
  2. inArray([...]) -将返回与过滤数组匹配的项目数组。

像这样:

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

console.log( arr.filter(f(inBetween(3, 6))) ); // 3,4,5,6
console.log( arr.filter(f(inArray([1, 2, 10]))) ); // 1,2
Run Code Online (Sandbox Code Playgroud)

我试过这个功能:

function f(item) {
  let result = [];

  function inBetween(from, to){
    if (item >= from && item <= to){
      result.push(item);
    }
  }

  function inArray(array){
    if (array.indexOf(item) >= 0){
      result.push(item);
    }
  }

  return result;
}
Run Code Online (Sandbox Code Playgroud)

但我不知道如何将我的功能附加到filter。它给出了这个错误:

console.log(arr.filter(f(inBetween(3,6)))); // 3,4,5,6

ReferenceError:未定义inBetween

有可能吗?

Jos*_*eph 9

array.filter()需要一个功能。如果要预绑定一些参数,则需要一个返回函数的函数。在这种情况下,inBetweeninArray都应返回函数。

因此应该是:

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

function inBetween(min, max) {
  return function(value) {
    // When this is called by array.filter(), it can use min and max.
    return min <= value && value <= max
  }
}

function inArray(array) {
  return function(value) {
    // When this is called by array.filter(), it can use array.
    return array.includes(value)
  }
}

console.log( arr.filter(inBetween(3, 6)) )
console.log( arr.filter(inArray([1, 2, 10])) )
Run Code Online (Sandbox Code Playgroud)

在这种情况下,minmax,和array近在返回的功能,这样当array.filter()调用返回的功能,它可以访问这些值。


您的inArray()功能已由本机实现array.includes()