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


当前回答

Let departments是一个数组。您要从此数组中删除一项。

departments: string[] = [];

 removeDepartment(name: string): void {
    this.departments = this.departments.filter(item => item != name);
  }

其他回答

let a: number[] = [];

a.push(1);
a.push(2);
a.push(3);

let index: number = a.findIndex(a => a === 1);

if (index != -1) {
    a.splice(index, 1);
}

console.log(a);

和在JavaScript中一样。

delete myArray[key];

注意,这将元素设置为undefined。

最好使用Array.prototype.splice函数:

const index = myArray.indexOf(key, 0);
if (index > -1) {
   myArray.splice(index, 1);
}
let foo_object; // Itemitem(object here) to remove
this.foo_objects = this.foo_objects.filter(obj => return obj !== foo_object);

类似于Abdus Salam Azad的答案,但将数组作为参数 / / https://love2dev.com/blog/javascript-remove-from-array/

function arrayRemove(arr:[], value:any) { 
    
    return arr.filter(function(ele){ 
        return ele != value; 
    });
}

这对我很管用。

你的数组:

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);
}