javascript - 尽管函数返回 false,Array.filter() 仍不过滤元素

标签 javascript angular

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

下面的代码似乎没有过滤掉我想要的元素,尽管过滤器函数为该元素返回 false 。至少我认为它会返回 false,因为比较结果为 false(请参阅输出)。

带有 Array.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);
        //  }
        // });
      });
  }

第一部分的输出:

Array[0: Object { id: 37 }]
Object { id: 37 }
Object { id: 37 }
false
Array[0: Object { id: 37 }]

最佳答案

Array.filter 返回一个包含过滤值的新数组,它不会更改调用它的实例,请检查 documentation

所以你想做类似的事情

this.char.altchars = this.char.altchars.filter(ac => ac != this.altChar);

关于javascript - 尽管函数返回 false,Array.filter() 仍不过滤元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51973769/

相关文章:

javascript - 如何使用 Ajax/Ruby on Rails 在 View 中呈现 Controller 变量?

javascript - 在 Javascript 中访问对象时自动调用函数

javascript - 将图像相对放置在文本上方或下方。

angular - 无法在 ionic 功能之外获得 promise 值

node.js - 无需 npm 手动安装 Angular 5 模块

javascript - 向 Javascript 日期添加时间

angular - 如何销毁 Angular 组件?

导航后Angular 6重定向回主页

angular - map 运算符不适用于 AngularFireAuth Observable

javascript - JavaScript 是否会在每次调用函数时都对其进行编译?