Angular 数组过滤器无法处理字符串列表

Angular array filter is not working on a list of string

我有一个字符串数组,想在一些操作后过滤掉特定的字符串。但是,我好像哪里做错了。

this.displayUser.followers.filter(userId=>userId !== this.loggedUser.userid);

在这里,followers 是一个字符串数组 -> string[] 并且在执行某些操作(例如,取消关注)时;我想从显示的用户的关注者列表中删除登录用户的 ID。 不过这个过滤操作好像不行。

另一方面,我尝试使用 splice,效果非常好。

this.displayUser.followers.splice(
      this.displayUser.followers.findIndex(userId=>userId === this.loggedUser.userid)
 ,1);

我无法理解我在第一种方法中做错了什么?

Array.filter 不会更改对其执行操作的数组,但 returns 会更改其值已通过条件的新数组。 为了使用 .filter 并保存结果,你可以这样做:

this.displayUser.followers = this.displayUser.followers.filter((userId) => userId !== this.loggedUser.userid);

这将删除 userId === loggedUser.userid.

中的所有条目 另一方面,

.splice 操纵它对其执行操作的数组,因此您将立即看到预期的结果。