角4拼接始终删除数组中的最后一个元素 [英] angular 4 splice always deletes last element from array
问题描述
我有一个奇怪的问题,即出于某些原因,即使alert
提供正确的索引,拼接也总是从数组中删除最后一个元素.
I have a weird problem where for some reason splice always deletes last element from array, even though the alert
gives correct index.
onRemove()
方法是删除的方法.
<button (click)="onAdd()">Add</button>
<ul>
<li *ngFor="let course of courses; index as i; even as isEven">
{{ i }} - {{ course.name }} <span *ngIf="isEven">(EVEN)</span>
<button (click)="onRemove(course)">Remove</button>
</li>
</ul>
export class AppComponent {
courses = [
{ id: 1, name: 'course1' },
{ id: 2, name: 'course2' },
{ id: 3, name: 'course3' },
];
onAdd() {
this.courses.push({ id: 4, name: 'course4' });
}
onRemove(course) {
let index = this.courses.indexOf(course);
alert(index); // I get correct index here
this.courses.splice(index, 1);
}
}
推荐答案
逻辑是正确的.我认为您正在查看的角度可能是问题所在.单击它会删除正确的元素.
The logic is correct. I think the angle you are looking at it could be the problem. It is removing the correct element when you click on it.
例如,假设您在数组中具有3个元素,并且以下上下文索引从0开始.
For example, consider that you have 3 elements in the array with the following contexts index starting from 0.
0 - course1
1 - course2
2 - course3
当您删除索引为1的元素时,元素总数变为2,结果索引也随之更改.
When You remove element with index 1, the total number of elements becomes two and as a result the index changes as well.
0 - course1
1 - course3
因此,您可以认为它总是删除最后一个元素,而实际上,它只是在移动数组的位置.
So this can get you to think that it is always deleting the last element whereas in reality it is just shifting the position of the array.
以下代码可能是您想要实现的.只需将第一个字符串插值更改为{{course.id}}
而不是{{i}}
The following code could be what you are trying to achieve. Just change the first string interpolation to {{course.id}}
instead of {{i}}
<li *ngFor="let course of courses; index as i; even as isEven">
{{ course.id }} - {{ course.name }} <span *ngIf="isEven">(EVEN)</span>
<button (click)="onRemove(course)">Remove</button>
</li>
希望这会有所帮助
这篇关于角4拼接始终删除数组中的最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!