如何删除 TypeScript 中的数组项? [英] How do I remove an array item in TypeScript?

查看:65
本文介绍了如何删除 TypeScript 中的数组项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在 TypeScript 中创建的数组,它有一个我用作键的属性.如果我有那把钥匙,我怎样才能从中删除一个项目?

I have an array that I've created in TypeScript and it has a property that I use as a key. If I have that key, how can I remove an item from it?

推荐答案

与在 JavaScript 中的方式相同.

Same way as you would in JavaScript.

delete myArray[key];

请注意,这会将元素设置为 undefined.

Note that this sets the element to undefined.

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

Better to use the Array.prototype.splice function:

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

这篇关于如何删除 TypeScript 中的数组项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆