我在TypeScript中创建了一个数组,它有一个属性,我把它用作键。如果我有那把钥匙,我怎么能从里面删除一个项目?
当前回答
可以在数组上使用splice方法删除元素。
例如,如果你有一个名为arr的数组,使用以下方法:
arr.splice(2, 1);
因此,这里索引为2的元素将是起点,参数2将决定删除多少个元素。
如果你想删除名为arr的数组的最后一个元素,那么这样做:
arr.splice(arr.length-1, 1);
这将返回删除最后一个元素的arr。
例子:
var arr = ["orange", "mango", "banana", "sugar", "tea"];
arr.splice(arr.length-1, 1)
console.log(arr); // return ["orange", "mango", "banana", "sugar"]
其他回答
在ES6中,你可以使用以下代码:
removeDocument(doc){
this.documents.forEach( (item, index) => {
if(item === doc) this.documents.splice(index,1);
});
}
我看到许多抱怨,删除方法不是内置的。考虑使用Set而不是array——它有内置的添加和删除方法。
我们可以使用筛选器和包含来实现逻辑
const checkAlpha2Code = ['BD', 'NZ', 'IN'] let countryAlpha2Code = ['US', 'CA', 'BD', 'NZ', 'AF' , 'AR' , 'BR'] /** * Returns the modified array countryAlpha2Code * after removing elements which matches with the checkAlpha2Code */ countryAlpha2Code = countryAlpha2Code.filter(alpha2code => { return !checkAlpha2Code.includes(alpha2code); }); console.log(countryAlpha2Code) // Output: [ 'US', 'CA', 'AF', 'AR', 'BR' ] // Resetting the values again countryAlpha2Code = ['US', 'CA', 'BD', 'NZ', 'AF' , 'AR' , 'BR'] /** * Returns the modified array countryAlpha2Code * which only matches elements with the checkAlpha2Code */ countryAlpha2Code = countryAlpha2Code.filter(alpha2code => { return checkAlpha2Code.includes(alpha2code); }); console.log(countryAlpha2Code) // Output: [ 'BD', 'NZ' ]
下面是一个简单的一行代码,用于按属性从对象数组中删除对象。
delete this.items[this.items.findIndex(item => item.item_id == item_id)];
or
this.items = this.items.filter(item => item.item_id !== item.item_id);
您可以尝试先获取列表或数组的索引或位置,然后使用for循环将当前数组分配给临时列表,过滤掉不想要的项并将想要的项存储回原始数组
removeItem(index) {
var tempList = this.uploadFile;
this.uploadFile = [];
for (var j = 0; j < tempList.length; j++) {
if (j != index)
this.uploadFile.push(tempList[j]);
}
}
推荐文章
- 如何读一个文本文件到一个列表或数组与Python
- 如何在Python中将十六进制字符串转换为字节?
- 获取函数的返回类型
- 为什么是事件。目标不是元素在Typescript?
- 与push()相反;
- 如何生成。d。ts“typings”定义文件从现有的JavaScript库?
- 用“+”(数组联合运算符)合并两个数组如何工作?
- 在定义文件(*d.ts)中导入类
- 如何在Angular 2.0中使用/创建动态模板来编译动态组件?
- 在typescript中一直使用。tsx而不是。ts有什么缺点吗?
- 如何使用this.router.parent.navigate('/about')导航到另一个路由?
- 在Java中保存最后N个元素的大小有限的队列
- 使arrayList.toArray()返回更具体的类型
- 如何从对象数组中通过对象属性找到条目?
- 如何从关联数组中删除键及其值?