我想使用typescript从数组中批量删除。
我是通过使用for循环来完成的。
this.versions = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
this.selectedVersions = [1, 2, 3, 4, 5, 6];
for (let i = 0; i < this.selectedVersions.length; i++) {
this.versions = this.removeObjectFromArray(this.versions, this.selectedVersions[i]);
}
//removing a object from array
removeObjectFromArray(listOfdata: any, data: any) {
let index = listOfdata.findIndex(function (o) {
return o === data;
})
listOfdata.splice(index, 1);
return listOfdata;
}
但我不喜欢使用for loop
。所以让我知道如何使用typescript在数组中进行批量删除。
答案 0 :(得分:4)
您可以使用数组过滤器:
var versions = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
var selectedVersions = [1, 2, 3, 4, 5, 6];
versions = versions.filter(el => !selectedVersions.includes(el));
console.log(versions);
&#13;
答案 1 :(得分:2)
利用array.filter
并根据条件
let versions = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
let selectedVersions = [1, 2, 3, 4, 5, 6];
versions = versions.filter(arrayVal => selectedVersions.indexOf(arrayVal) == -1 );
// checks for the values of selected Versions agains each value of versions and returns accordindly
console.log(versions)
&#13;
答案 2 :(得分:2)
使用过滤器
// will only keep elements that are not included in selectedVersions
this.versions = this.versions.filter(i => !this.selectedVersions.includes(i));
答案 3 :(得分:1)
我认为您可以使用indexOf,如下所示:
this.versions = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
this.selectedVersions = [1, 2, 3, 4, 5, 6];
for (let i = 0; i < this.selectedVersions.length; i++)
{
if(this.versions.indexOf(this.selectedVersions[i])!==-1){
this.versions.splice(index, 1);
}
}
答案 4 :(得分:1)
我个人会使用过滤器来保存原始数组:
let nonSelectedVersions = this.versions.filter((e) => this.selectedVersions.indexOf(e) !== -1);
答案 5 :(得分:0)
使用array.filter()而不是for循环
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
答案 6 :(得分:0)
Typescript与javascript相同,你可以从JS获得你所有的知识。
How do I remove a particular element from an array in JavaScript?
如果TS编译器支持
,也可以使用for-of循环var versions = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
var selectedVersions = [1, 2, 3, 4, 5, 6];
for ( val of selectedVersions) {
if(selectedVersions.indexOf(val)!=-1){
versions.splice(versions.indexOf(val), 1);
}
}