javascript - 使用闭包进行多项选择的数组过滤器函数 - Javascript

标签 javascript arrays filter closures

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

  1. inBetween(a, b) - 将返回 ab
  2. 之间的数组
  3. 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

我试过这个功能:

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;
}

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

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

ReferenceError: inBetween is not defined

这有可能吗?

最佳答案

array.filter() 需要一个函数。如果你想预绑定(bind)一些参数,你需要一个返回函数的函数。在这种情况下,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])) )

在这种情况下,minmaxarray 关闭返回的函数,这样当 array.filter() 调用返回的函数,它可以访问这些值。


您的 inArray() 功能已由 native array.includes() 实现。

关于javascript - 使用闭包进行多项选择的数组过滤器函数 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58148707/

相关文章:

PHP GET变量数组注入(inject)

php - 解码 CS :GO match sharing code with PHP

javascript - $ ('#textboxId' ).val() 返回旧值(浏览器缓存问题)

javascript - 添加点击操作以搜索 Bootstrap

javascript - instanceof 在 JSON.stringify() 中的行为有何不同?

java - Hibernate 过滤器的默认条件

Haskell 长度和滤波器确定直线的凸度或凹度

javascript - Froala Editor 2 basic init 未捕获类型错误 : undefined is not a function

java - 无法退出while循环

jquery - 使用 Jquery Isotope 插件动态插入项目后,如何将默认过滤器应用于容器?