简体   繁体   English

为什么 function 返回过滤后的 boolean 数组

[英]Why function returns filtered boolean array

I learn js and trying to write filter method without using it.我学习 js 并尝试在不使用它的情况下编写过滤器方法。 So I need to my function return filtered array based on function, which passed as a parameter.所以我需要我的 function 返回基于 function 的过滤数组,它作为参数传递。 And it does but it's returned boolean array and I don't understand why.它确实如此,但它返回了 boolean 数组,我不明白为什么。

My code:我的代码:

 function myFilter(arr, func) {
      const result = [];
        for (let el of arr) {
            result.push(func(el));
        }
        return result;
    }

Calling with some numbers:拨打一些号码:

myFilter([2, 5, 1, 3, 8, 6], function(el) { return el > 3 })

It should've returned [5, 8, 6] but instead I got [false, true, false, true, true].它应该返回 [5, 8, 6] 但我得到了 [false, true, false, true, true]。 I don't get why can someone please explain it to me?我不明白为什么有人可以向我解释一下?

It's returning a boolean array because you're pushing booleans into the result array.它返回一个 boolean 数组,因为您将布尔值推入result数组。 func(el) or function(el) { return el > 3 } returns a boolean. func(el)function(el) { return el > 3 }返回 boolean。

What you want is to push elements/numbers into the result array based on the condition of func(el)您想要的是根据func(el)的条件将元素/数字推入result数组

Try尝试

function myFilter(arr, func) {
    const result = [];
    for (let el of arr) {
        if (func(el)) {
            result.push(el);
        }
    }
    return result;
}

Better use the javascript inbuit filter func, you dont need one of your own:最好使用 javascript inbuit 过滤器功能,您不需要自己的一个:

 const filtered = [2, 5, 1, 3, 8, 6].filter(el => el > 3) console.log(filtered)

1st You need to return after the condition true or false, Ex. 1st 您需要在条件 true 或 false 之后返回,例如。 For in your case,对于你的情况,

myFilter([2, 5, 1, 3, 8, 6], function(el) { return  el > 3 && el  });

2nd You need to check wether the values true or not, For Ex.第二,您需要检查值是否正确,例如。 in your case,在你的情况下,

for (let el of arr) {
  if (func(el))
    result.push(func(el));
  }
}

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

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