splice总是删除数组

时间:2017-12-25 10:16:45

标签: angular typescript

我尝试了很多搜索,如何删除数组项目给它的索引位置但是徒劳无功。 拼接总是从数组中删除最后一项,虽然我提供了需要删除的项目的索引位置。(这里我知道要删除的项目的索引位置。以下是我的代码。

//Array declaration and value assignment

  let a: Product = {} as any;
  a.id='E001';
  a.name='EarPhone';
  a.price='230$';
  a.qty='20';
  a.tax='10.222';
  a.total='2222.22';
  this.product.push(a);  //pushing data to product array
  a.id='E002';
  a.name='HeadPhone';
  a.price='230$';
  a.qty='20';
  a.tax='10.222';
  a.total='2222.22';
  this.product.push(a);
  a.id='E003';
  a.name='MicroPhone';
  a.price='230$';
  a.qty='20';
  a.tax='10.222';
  a.total='2222.22';
  this.product.push(a);

/*   Required: Now i want to delete data in index position 1 that is 'E002', for which i have used slice function like this.
*/


//code to delete array item of particular index
void deletedItem()
{
//INDEX POSITION IS ONE HERE
this.product.splice(indexPosition,1);
}

但它总是删除最后一个索引中的项目,该项目是id ='E003';

注意:下面的链接没有给出我想要的答案 angular 4 splice always deletes last element from array

1 个答案:

答案 0 :(得分:1)

我假设你在具有异步事件'陷阱的循环中落入'反变量:

示例:

for(var i=0; i<10; i++) {
    var el = createElement(...);
    el.on('click', ()=> deleteItem(i));
}

在这种情况下,当执行click时,我将为10,因为循环在调用deleteItem之前完成

有不同的方法可以避免这种情况。 Imho,最优雅的解决方案是将循环代码移动到不同的方法或函数中:

function createRow(i) {
    // i will always be the value you passed as parameter, so the value at the time of the row creation.
    var el = createElement(...);
    el.on('click', ()=> deleteItem(i));
}
for(var i=0; i<10; i++) {
    createRow(i);
}