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屋!