【问题标题】:Filter not working when filtering an array in an object过滤对象中的数组时过滤器不起作用
【发布时间】:2021-08-03 05:04:10
【问题描述】:

我正在尝试过滤字符串数组

unfollow(handle: any) {
  let following = this.user?.following || [];
  following.filter((userHandle) => userHandle !== handle);
  console.log(following);
}

我想过滤用户对象中的以下数组,但是当我console.log(following) 时,数组没有改变。我尝试了不同的东西,包括this.user?.following?.filter((userHandle) => userHandle !== handle);,但没有过滤掉任何东西

【问题讨论】:

  • @froston 一个用户正在关注 2 个玩家 this.user?.following = ["ronaldo", "messi"] 然后例如这个用户决定 unfollow("messi") 所以我只是想通过过滤掉“messi”来更新数组

标签: arrays angular typescript filter


【解决方案1】:

您需要将过滤后的输出分配给其他变量。过滤器将返回包含过滤结果的新数组

unfollow(handle: any) {
  let following = this.user?.following || [];
 let newArray =  following.filter((userHandle) => userHandle !== handle);
  console.log(newArray);
}

【讨论】:

    【解决方案2】:

    Array.filter 返回一个新数组,而不是改变现有数组。

    试试:

    unfollow(handle: any) {
      let following = this.user?.following || [];
      let filtered = following.filter((userHandle) => userHandle !== handle);
      console.log(filtered);
    }
    

    或者没有可选的链接:

    unfollow(handle: any) {
      if (this.user) {
        let following = this.user.following || [];
        let filtered = following.filter((userHandle) => userHandle !== handle);
        this.user.following = filtered
      }
    }
    

    【讨论】:

    • 是的,这就是我所缺少的,但现在我该如何更新this.user?.following?如果我尝试这样做this.user?.following = filtered 我会收到此错误The left-hand side of an assignment expression may not be an optional property access.
    • 这似乎是另一个问题。您必须将其分配给 this.user.following,避免使用 ? 可选链接运算符。
    • 根据您的需要更新了答案。
    【解决方案3】:

    根据Array.prototype.filter() 的文档,

    filter() 方法创建一个新数组,其中包含所有通过所提供函数实现的测试的元素。

    因此,您需要存储filter() 的输出以在其他任何地方使用它,包括console.log()

    let filtered = following.filter((userHandle) => userHandle !== handle);

    【讨论】:

      猜你喜欢
      • 2021-03-21
      • 1970-01-01
      • 1970-01-01
      • 2022-12-02
      • 1970-01-01
      • 2020-05-25
      • 2020-05-30
      • 1970-01-01
      • 2023-01-02
      相关资源
      最近更新 更多