javascript过滤falsey值; Array.prototype.filter问题

//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 "" or false. You get the same as ele=>ele if you do ele=>ele!=false

If you use ===true then none of them is equal to true (type and value have to match true)

If you use ==true then you still don't get anything because none of them evaluate to true (here the value 1 would pass the test)

点赞
评论
卟~怕
卟~怕

您需要指定false条件

function bouncer(arr) {
  return arr.filter(ele => ele===false?false:true);
}
console.log(bouncer([0, "ate", "", false, 9]));
点赞
评论
noptio
noptio

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.

点赞
评论