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


当前回答

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

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

其他回答

Typescript/Javascript中的多个选项可以从数组中删除一个元素。 拼接是最好的选择

它在不创建新对象的情况下删除内联 它正确地更新数组的长度(不会留下空白的null元素)

下面是一个使用Splice函数根据对象数组中的某个字段删除对象的示例

Const persons = [ { 名字:“约翰”, 姓:“米歇尔” }, { 名字:“威廉”, 姓:“斯科特。” }, { 名字:“阿曼达”, 姓:“裁缝” } ] console.log('删除前:'+JSON.stringify(persons)); console.log(“删除威廉:”); persons.splice(人。findIndex(item => item。firstName === 'William'),1); console.log('After Deleting William'+JSON.stringify(persons));

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

如果你需要从数组中删除一个给定的对象,并且你想确定以下情况,请使用此方法:

列表没有重新初始化 正确更新数组长度

    const objWithIdToRemove;
    const objIndex = this.objectsArray.findIndex(obj => obj.id === objWithIdToRemove);
    if (objIndex > -1) {
      this.objectsArray.splice(objIndex, 1);
    }