在数组中使用 slice 不会影响模板
using slice in an array doesn't affect the template
我有一个数组 availableBoats
,我正在使用以下代码片段呈现它的元素:
<app-boat *ngFor="let b of availableBoats" [size]="b.size" [(available)]="b.available" [type]="b.type" ></app-boat>
我原以为当我使用 .slice()
函数从数组中删除一艘船时,它不会再出现在模板中。我是不是做错了什么,或者这不是 Angular 中的预期行为?
在某些时候,调用了以下代码。我测试了它,在那里设置了一个断点,我可以看到船被移除了:
for (let i = 0; i < this.availableBoats.length; i++) {
const b = this.availableBoats[i];
if (b.type === this.selectedBoatType) {
this.availableBoats.slice(i, 1);
return;
}
}
I was expecting that when I remove one boat from the array using the
.slice() function, it won't appear anymore in the template.
您的假设不正确,因为 slice
(...) returns a shallow copy of a portion of an array into a new array
object selected from begin to end (end not included). The original
array will not be modified.
为了改变数组,你需要使用 splice
which
(...) changes the contents of an array by removing existing elements
and/or adding new elements
因此 this.availableBoats.slice(i, 1);
没有从 this.availableBoats
中删除任何元素。
为此使用 this.availableBoats.splice(i, 1);
我有一个数组 availableBoats
,我正在使用以下代码片段呈现它的元素:
<app-boat *ngFor="let b of availableBoats" [size]="b.size" [(available)]="b.available" [type]="b.type" ></app-boat>
我原以为当我使用 .slice()
函数从数组中删除一艘船时,它不会再出现在模板中。我是不是做错了什么,或者这不是 Angular 中的预期行为?
在某些时候,调用了以下代码。我测试了它,在那里设置了一个断点,我可以看到船被移除了:
for (let i = 0; i < this.availableBoats.length; i++) {
const b = this.availableBoats[i];
if (b.type === this.selectedBoatType) {
this.availableBoats.slice(i, 1);
return;
}
}
I was expecting that when I remove one boat from the array using the .slice() function, it won't appear anymore in the template.
您的假设不正确,因为 slice
(...) returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.
为了改变数组,你需要使用 splice
which
(...) changes the contents of an array by removing existing elements and/or adding new elements
因此 this.availableBoats.slice(i, 1);
没有从 this.availableBoats
中删除任何元素。
为此使用 this.availableBoats.splice(i, 1);