0

我有一个字符串数组,并且想在某些操作后过滤掉一个特定的字符串。但是,似乎我在那里做错了什么。

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);

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

4

1 回答 1

0

Array.filter不会更改它对其执行操作的数组,而是返回一个新数组,其中包含通过条件的值。为了使用.filter并保存结果,您可以执行以下操作:

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

这将删除所有条目,其中userId === loggedUser.userid.

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

于 2020-08-11T06:22:36.700 回答