如何在TypeScript中删除数组项?

本文翻译自:How do I remove an array item in TypeScript?

I have an array that I've created in TypeScript and it has a property that I use as a key. 我有一个在TypeScript中创建的数组,它具有一个用作键的属性。 If I have that key, how can I remove an item from it? 如果我有该钥匙,如何从中删除一个物品?


#1楼

参考:https://stackoom.com/question/12ADe/如何在TypeScript中删除数组项


#2楼

Same way as you would in JavaScript. 与JavaScript中的方式相同。

delete myArray[key];

Note that this sets the element to undefined . 请注意,这会将元素设置为undefined

Better to use the Array.prototype.splice function: 最好使用Array.prototype.splice函数:

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

#3楼

If array is type of objects, then the simplest way is 如果数组是对象的类型,那么最简单的方法是

let foo_object // Item to remove
this.foo_objects = this.foo_objects.filter(obj => obj !== foo_object);

#4楼

It is my solution for that: 这是我的解决方案:

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

#5楼

With ES6 you can use this code : 使用ES6,您可以使用以下代码:

removeDocument(doc){
   this.documents.forEach( (item, index) => {
     if(item === doc) this.documents.splice(index,1);
   });
}

#6楼

You can use the splice method on an array to remove the elements. 您可以在数组上使用splice方法删除元素。

for example if you have an array with the name arr use the following: 例如,如果您有一个名为arr的数组,请使用以下命令:

arr.splice(2,1);

so here the element with index 2 will be the starting point and the argument 2 will determine how many elements to be deleted. 因此这里索引为2的元素将作为起点,而参数2将确定要删除的元素数。

If you want to delete the last element of the array named arr then do this: 如果要删除名为arr的数组的最后一个元素,请执行以下操作:

arr.splice(arr.length,1);

This will return arr with the last element deleted. 这将返回arr并删除最后一个元素。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值