我需要为过滤器创建一个函数,它必须有 2 个选择。
inBetween(a, b)
- 将返回a
和b
之间的数组
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)一些参数,你需要一个返回函数的函数。在这种情况下,inBetween
和 inArray
都应该返回函数。
所以应该是:
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])) )
在这种情况下,min
、max
和 array
关闭返回的函数,这样当 array.filter()
调用返回的函数,它可以访问这些值。
您的 inArray()
功能已由 native array.includes()
实现。
关于javascript - 使用闭包进行多项选择的数组过滤器函数 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58148707/