我在TypeScript中创建了一个数组,它有一个属性,我把它用作键。如果我有那把钥匙,我怎么能从里面删除一个项目?
当前回答
类似于Abdus Salam Azad的答案,但将数组作为参数 / / https://love2dev.com/blog/javascript-remove-from-array/
function arrayRemove(arr:[], value:any) {
return arr.filter(function(ele){
return ele != value;
});
}
其他回答
在ES6中,你可以使用以下代码:
removeDocument(doc){
this.documents.forEach( (item, index) => {
if(item === doc) this.documents.splice(index,1);
});
}
我们可以使用筛选器和包含来实现逻辑
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' ]
我看到许多抱怨,删除方法不是内置的。考虑使用Set而不是array——它有内置的添加和删除方法。
这是我的解决方案:
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();
}
如果你需要从数组中删除一个给定的对象,并且你想确定以下情况,请使用此方法:
列表没有重新初始化 正确更新数组长度
const objWithIdToRemove;
const objIndex = this.objectsArray.findIndex(obj => obj.id === objWithIdToRemove);
if (objIndex > -1) {
this.objectsArray.splice(objIndex, 1);
}
推荐文章
- 'React'指的是一个UMD全局,但当前文件是一个模块
- Angular 2中的“component”不是一个已知的元素
- 什么Java 8流。收集等价物可在标准Kotlin库?
- 比较JUnit断言中的数组,简洁的内置方式?
- 数组到哈希Ruby
- 将Set<T>转换为List<T>的最简洁的方法
- TypeScript错误:属性“X”在类型“Window”上不存在
- Java 8流和数组操作
- 在javascript中从平面数组构建树数组
- 从另一个列表id中排序一个列表
- 我怎么能计算在打字稿2日期之间的时间
- 在bash中传递数组作为参数
- 正确使用错误
- 如何在c++中初始化一个向量
- 用any可以吗?'来检查数组是否为空?