简体   繁体   English

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

[英]Array.filter() does not filter element despite function returning false

I'm trying to use the filter function to remove an element from an array. 我正在尝试使用过滤器功能从数组中删除一个元素。 This is in Typescript/Angular6 but I think this snippet applies to JS in general. 这是在Typescript / Angular6中,但我认为此代码段通常适用于JS。

Below code does not seem to filter out the element I want despite the filter function returning false for that element. 下面的代码似乎没有过滤掉我想要的元素,尽管过滤器函数对该元素返回了false At least I think it returns false as the comparison evaluates to false (see output). 至少我认为它会返回false因为比较结果为false(请参见输出)。

The verbose manual function with Array.splice() does do its job. Array.splice()的详细手动功能可以完成其工作。 What am I not seeing? 我没看到什么?

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

output from first part: 第一部分的输出:

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

Array.filter returns a new array with the filtered values, it doesn't change the instance it's invoked on, check the documentation Array.filter返回带有过滤值的新数组,它不会更改其调用的实例,请查看文档

So you would wanna do something like that 所以你想做这样的事情

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

Array.filter returns a new array, thus you need assign result of filter to some variable. Array.filter返回一个新数组,因此您需要将filter的结果分配给某个变量。

this.char.altchars = this.char.altchars.filter(ac => {
     console.log(ac);
     console.log(this.altChar);
     console.log(this.altChar != ac);
     return ac != this.altChar;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM