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


当前回答

使用TypeScript扩展运算符(…)

// Your key
const key = 'two';

// Your array
const arr = [
    'one',
    'two',
    'three'
];

// Get either the index or -1
const index = arr.indexOf(key); // returns 0


// Despite a real index, or -1, use spread operator and Array.prototype.slice()    
const newArray = (index > -1) ? [
    ...arr.slice(0, index),
    ...arr.slice(index + 1)
] : arr;

其他回答

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

let updatedArray = [];
for (let el of this.oldArray) {
    if (el !== elementToRemove) {
        updated.push(el);
    }
}
this.oldArray = updated;
function myFunction(ID){ 
let index = this.myArray.findIndex(d => d.ID === ID); //find index in your array
        console.log('index==',index);
        if (index > -1) {
          console.log('remaving at',index);
          this.myArray.splice(index, 1);//remove element from array
        }
}

注意:你的数组必须有一个名为ID…否则将返回-1,表示未找到

let foo_object; // Itemitem(object here) to remove
this.foo_objects = this.foo_objects.filter(obj => return obj !== foo_object);

和在JavaScript中一样。

delete myArray[key];

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

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

const index = myArray.indexOf(key, 0);
if (index > -1) {
   myArray.splice(index, 1);
}

这是我的解决方案:

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