简体   繁体   English

用参数 Function 过滤数组之间的数字

[英]Filter numbers between Array with Parameter Function

I am trying to work with Arrays and.filter() function. I need to filter between parameters on a function to get it to the correct output. I can't seem to get my NPM test to pass.我正在尝试使用 Arrays 和.filter() function。我需要在 function 的参数之间进行过滤,以使其成为正确的 output。我似乎无法通过 NPM 测试。 I can see the output seems correct, but the error I am getting is [object Array] is not a function at Array.filter Does anyone know where I am going wrong?我可以看到 output 似乎是正确的,但我得到的错误是 [object Array] is not a function at Array.filter 有人知道我哪里出错了吗?

here is the code:这是代码:

function betweenArray(c, d){
    
    let filterNumbers = arr.filter(function(currentElement) {
        if (currentElement >= c && currentElement <= d)
        return currentElement 
    })

    return filterNumbers
}

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

console.log(arr.filter(betweenArray(4, 10))); // 2, 3, 4, 5, 6, 7

So, Array.filter takes a function that should return either true or false (ie a predicate function).因此, Array.filter需要一个 function,它应该返回truefalse (即谓词函数)。 If the function returns true the item is projected into the resulting array.如果 function 返回true ,则该项目将投影到结果数组中。 If the function returns false, it is omitted from the resulting array.如果 function 返回 false,则它会从结果数组中省略。

You want a function that creates this predicate function.您需要一个 function 来创建此谓词 function。

Using arrow function notation , you can write this as:使用箭头 function notation ,您可以将其写为:

const between = (min, max) => (v) => v >= min && v <= max;

Now you can use it:现在你可以使用它了:

 const between = (min, max) => (v) => v >= min && v <= max; let arr = [-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; console.log(arr.filter(between(-1, 3)));

Note:笔记:

The reason your predicate function (mostly) works您的谓词 function(大部分)起作用的原因

let filterNumbers = arr.filter(function(currentElement) {
    if (currentElement >= a && currentElement <= b)
        return currentElement 
})

is because any non-zero number is coerced to true and undefined is coerced to false .是因为任何非零数字都被强制为trueundefined被强制为false

Now let's try your version of the predicate function with a range that traverses zero and observe how it breaks :现在让我们尝试使用遍历零的范围的谓词 function 的版本,并观察它是如何中断的

 const between = (min, max) => function(currentElement) { if (currentElement >= min && currentElement <= max) return currentElement // this value isn't `true`, it's a number // `undefined` implicitly returned here } let arr = [-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; console.log(arr.filter(between(-1, 3))); // no zero here??!

Where did zero go?零go去哪儿了? Can you figure out why it breaks?你能弄清楚它为什么会坏吗?

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

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