我在TypeScript中创建了一个数组,它有一个属性,我把它用作键。如果我有那把钥匙,我怎么能从里面删除一个项目?


当前回答

只是想为数组添加扩展方法。

interface Array<T> {
      remove(element: T): Array<T>;
    }

    Array.prototype.remove = function (element) {
      const index = this.indexOf(element, 0);
      if (index > -1) {
        return this.splice(index, 1);
      }
      return this;
    };

其他回答

可以在数组上使用splice方法删除元素。

例如,如果你有一个名为arr的数组,使用以下方法:

arr.splice(2, 1);

因此,这里索引为2的元素将是起点,参数2将决定删除多少个元素。

如果你想删除名为arr的数组的最后一个元素,那么这样做:

arr.splice(arr.length-1, 1);

这将返回删除最后一个元素的arr。

例子:

var arr = ["orange", "mango", "banana", "sugar", "tea"];
arr.splice(arr.length-1, 1)
console.log(arr); // return ["orange", "mango", "banana", "sugar"]

还有一个使用Typescript的解决方案:

let updatedArray = [];
for (let el of this.oldArray) {
    if (el !== elementToRemove) {
        updated.push(el);
    }
}
this.oldArray = updated;

这对我很管用。

你的数组:

DummyArray: any = [
    { "id": 1, "name": 'A' },
    { "id": 2, "name": 'B' },
    { "id": 3, "name": 'C' },
    { "id": 4, "name": 'D' }
]

功能:

remove() {
    this.DummyArray = this.DummyArray.filter(item => item !== item);
}

注意:这个函数删除数组中的所有对象。如果你想从数组中删除一个特定的对象,那么使用这个方法:

remove(id) {
    this.DummyArray = this.DummyArray.filter(item => item.id !== id);
}

这是我的解决方案:

onDelete(id: number) {
    this.service.delete(id).then(() => {
        let index = this.documents.findIndex(d => d.id === id); //find index in your array
        this.documents.splice(index, 1);//remove element from array
    });

    event.stopPropagation();
}

您可以尝试先获取列表或数组的索引或位置,然后使用for循环将当前数组分配给临时列表,过滤掉不想要的项并将想要的项存储回原始数组

removeItem(index) {
    var tempList = this.uploadFile;
    this.uploadFile = [];

    for (var j = 0; j < tempList.length; j++) {
      if (j != index)
        this.uploadFile.push(tempList[j]);
    }
  }