[英]Angular array filter is not working on a list of string
I have an array of string, and want to filter out a particular string after some operation.我有一个字符串数组,并且想在某些操作后过滤掉一个特定的字符串。 But, it seems I am doing something wrong there.
但是,似乎我在那里做错了什么。
this.displayUser.followers.filter(userId=>userId !== this.loggedUser.userid);
Here, followers is an array of string -> string[]
and upon some action (say, unfollow);在这里,followers 是一个字符串数组 ->
string[]
和一些动作(比如,取消关注); I want to remove the logged user's id from the displayed user's followers list.我想从显示的用户的关注者列表中删除登录用户的 ID。 However, this filter operation does not seem to work.
但是,此过滤器操作似乎不起作用。
On the other hand I tried using splice which is working perfectly fine.另一方面,我尝试使用 splice,它工作得非常好。
this.displayUser.followers.splice(
this.displayUser.followers.findIndex(userId=>userId === this.loggedUser.userid)
,1);
I am unable to understand what am I doing wrong in the first approach?我无法理解我在第一种方法中做错了什么?
Array.filter
does not change the array it performs its action on, but returns a new array with values that passed the condition. Array.filter
不会更改它对其执行操作的数组,但会返回一个新数组,其中包含通过条件的值。 In order to use .filter
and have the result saved, you can do:为了使用
.filter
并保存结果,您可以执行以下操作:
this.displayUser.followers = this.displayUser.followers.filter((userId) => userId !== this.loggedUser.userid);
This will remove all entries where userId === loggedUser.userid
.这将删除
userId === loggedUser.userid
的所有条目。
.splice
on the other hand manipulates the array it performs its actions on, hence you will immediately see the results as expected.另一方面,
.splice
操作它对其执行操作的数组,因此您将立即看到预期的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.