我正在尝试使用过滤函数从数组中删除元素。这是在 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/