Javascript Array.prototype.filter()不工作
我在客户端上运行了这段代码,用于过滤事件列表:Javascript Array.prototype.filter()不工作,javascript,arrays,Javascript,Arrays,我在客户端上运行了这段代码,用于过滤事件列表: if (res) { eventList.filter(function(event) { const out = res.find(function(visibility) { return visibility.ID == event.id; }) == undefined; return out; }); alert(eventList); } displayEvents(even
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
时,元素也不会被过滤掉
只是为了调试,我尝试在任何情况下返回false
,结果数组仍然具有所有初始元素:
eventList.filter(function(event) {
return out;
});
我在这里做错了什么
编辑:
res
是服务器返回的JSON对象数组(仅包含ID
字段),而eventList
是Facebook事件列表,从Facebook API请求传递给此回调函数。prototype.filter不更改当前的数组,它返回由满足所提供谓词的项组成的新数组。应该是这样的
var result = eventList.filter(function(event) {
return res.find(function(visibility) { return visibility.ID == event.id; }) === undefined;
});
您不需要声明和分配变量,然后从函数返回它,只需返回表达式即可。filter()不会更改原始数组。您需要执行
eventList=eventList.filter(..)
。还有,不要用alert()
进行调试。天哪,我怎么会这么蠢。。。谢谢