尽管函数返回 false,但 Array.filter() 不会过滤元素

blu*_*isk 0 javascript angular

我正在尝试使用 filter 函数从数组中删除一个元素。这是在 Typescript/Angular6 中,但我认为这个片段一般适用于 JS。

尽管过滤器函数false为该元素返回,但下面的代码似乎没有过滤掉我想要的元素。至少我认为它false在比较评估为 false时返回(参见输出)。

详细的手动功能 withArray.splice()确实可以完成它的工作。我没有看到什么?

  public deleteAltChar() {
    console.log(this.char.altchars);
    this.charService.deleteAltChar(this.altChar, this.char)
      .subscribe(data => {
        // THIS DOES NOT WORK
        this.char.altchars.filter(ac => {
            console.log(ac);
            console.log(this.altChar);
            console.log(this.altChar != ac);
            return ac != this.altChar;
        });
        console.log(this.char.altchars);
        // THIS DOES WORK
        // this.char.altchars.forEach(ac => {
        //  if (ac == this.altChar) {
        //      this.char.altchars.splice(this.char.altchars.indexOf(ac), 1);
        //  }
        // });
      });
  }
Run Code Online (Sandbox Code Playgroud)

第一部分的输出:

Array[0: Object { id: 37 }]
Object { id: 37 }
Object { id: 37 }
false
Array[0: Object { id: 37 }]
Run Code Online (Sandbox Code Playgroud)

abd*_*ady 5

Array.filter 返回一个带有过滤值的新数组,它不会改变它被调用的实例,检查文档

所以你会想做这样的事情

this.char.altchars = this.char.altchars.filter(ac => ac != this.altChar);
Run Code Online (Sandbox Code Playgroud)