【发布时间】:2020-02-22 08:59:09
【问题描述】:
转到这个StackBlitz Link (Not Working)
转到这个StackBlitz Link (Working Fine)
我的问题是关于Array.splice。
当数组数据不同但数组数据属于同一类型时,Array.splice 工作正常,Array.splice 仅删除最后一个索引。在这种情况下,splice 会忽略提供的索引以从数组中删除元素。
两个例子都有共同的 HTML 模板
<div class="container">
<table class="table table-dark table-striped table-hover">
<thead>
<tr>
<td scope="col"> Index </td>
<td scope="col"> Value </td>
<td scope="col"> Action </td>
</tr>
</thead>
<tbody>
<tr *ngFor="let row of rows; let i = index" [@itemAnim]>
<td> {{i}} </td>
<td>{{row}}</td>
<td><button class="btn btn-danger" (click)="deleteRow(i)">Delete</button></td>
</tr>
</tbody>
</table>
<button class="btn btn-primary " (click)="addRow()">Add row</button>
</div>
查看此示例按预期工作:
index = 1;
rows = [1];
addRow() {
this.rows.length > 0 ? this.index ++ : this.index = 1;
this.rows.push(this.index)
}
deleteRow(row: number) {
return this.rows.length > 0 ? this.rows.splice(row, 1) : this.index = 1;
}
这不起作用:
rows = [1];
addRow() {
this.rows.push(1)
}
deleteRow(row: number) {
this.rows.splice(row, 1) ;
}
在上面的代码中,当点击addButton 时,我只推送1。并且删除按钮仅从最后一个索引中删除,而不是提供行号索引。
我的问题是为什么会这样?上面的 stackBlitz 链接显示了同样的歧义。
【问题讨论】:
-
我认为这里有一个误解。尝试每次推送一个新号码,这样您就可以看到被删除的内容。 this stackblitz 是否消除了您的困惑? (从你的分叉而来)
-
你是对的。我已经在
See this example working as expected部分用粗体字提到了这一点。我的问题是.. 第二部分And this is not working:为什么推送相同的元素在splice中不起作用。 -
不工作是什么意思?能否详细说明。分叉的 stackblitz 使用你提到的代码不起作用。
-
如果你总是推送同一个元素,你怎么知道我的意思是哪个被删除了。
-
你将哪个参数传递给
deleteRow?尽管非现场参考可能会有所帮助,但请确保所有相关信息都在您的问题中,而不是在链接后面。
标签: javascript angular typescript