//removes falsey values from the array
function bouncer(arr) {
return arr.filter(ele => ele);
}
console.log(bouncer([0, "ate", "", false, 9]));
我不明白为什么“ ele”的条件在这里起作用。我只是返回参数,但不会通过该函数返回任何虚假参数,所以它可以工作...?为什么?同样,我不明白为什么我不能这样写: 返回arr.filter(ele => ele === true) 我的条件是:如果数组的元素为true,则将其返回,但这不起作用,我也不知道为什么。如果我尝试执行类似(ele => ele> 5)的过滤器,我会理解代码
Returning just "ele" will evaluate as true everything that is NOT false i.e. not
0
or""
orfalse
. You get the same asele=>ele
if you doele=>ele!=false
If you use
===true
then none of them is equal to true (type and value have to matchtrue
)If you use
==true
then you still don't get anything because none of them evaluate to true (here the value1
would pass the test)您需要指定false条件
It works because, you are using arrow function. So in your case
filter(ele => ele)
represents that you are only returning truthy values.Now this won't
(ele => ele>5)
beacause your array contains other values apart from integer.Also, for better clarity you can read arrow function expressions from here.