Javascript Array.prototype.filter() 不工作 [英] Javascript Array.prototype.filter() not working
问题描述
我在客户端上运行这段代码来过滤事件列表:
I have this piece of code running on the client that filters a list of events:
if (res)
{
eventList.filter(function(event) {
const out = res.find(function(visibility) { return visibility.ID == event.id; }) == undefined;
return out;
});
alert(eventList);
}
displayEvents(eventList);
问题是即使 out
为 false
元素也不会被过滤掉.
The problem is that even when out
is false
the element is not filtered out.
只是为了调试,我试图在任何情况下 return false
并且结果数组仍然包含所有初始元素:
Just for debug I tried to return false
in any case and the resulting array still had all the initial elements:
eventList.filter(function(event) {
return out;
});
我在这里做错了什么??
What am I doing wrong here??
res
是服务器返回的 JSON 对象数组(仅包含 ID
字段),而 eventList
是 Facebook 事件列表, 从 Facebook API 请求传递给这个回调函数
res
is an array of JSON objects (containg only ID
field) returned by the server, while eventList
is a list of Facebook events, passed to this callback function from a Facebook API request
推荐答案
Array.prototype.filter
不会就地更改数组,它返回由满足提供的谓词的项目组成的新数组.应该是这样的
Array.prototype.filter
does not change array inplace, it returns new array made of items that satisfies the provided predicate. It should look like this
var result = eventList.filter(function(event) {
return res.find(function(visibility) { return visibility.ID == event.id; }) === undefined;
});
你不需要声明和分配变量然后从函数中返回它,你可以简单地返回表达式
You don't need to declare and assign variable and then return it from function, you can simply return expression
这篇关于Javascript Array.prototype.filter() 不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!