Javascript从数组中删除元素

问题描述

JavaScript

this.crossCountries = this.api.getCrossCountries();
this.crossCountries.forEach(item => {
  this.crossCountriesData.push(item);

  for (var i = 0; i < this.crossCountriesData.length; i++) {
    if (this.crossCountriesData[i].response === 0) {
      this.crossCountriesData[i].response.shift();
    }
    this.crossCountriesData[i].response.splice(1,3);
    console.log('array: ',this.crossCountriesData[i].response);
  }
});

enter image description here

在移位和拼接之前,该数组有227个元素,现在有224个。 移位和拼接正在完成,但元素错误。

我需要删除数组的元素0、2、3和4。

我在做什么错了?

解决方法

我创建了一个示例数组,该数组具有我可以从您的问题中看到的值。如果运行下面的代码,您会发现索引0、2、3、4 已从原始数组。

检查我的解决方案,我添加了注释,以便更好地理解。

let arr = [
           {
              continent:"All",population:10000
           },{
              continent:"North-America",population:20000
           },{
              continent:"Europe",population:30000
           },{
            continent:"Asia",population:40000
           },{
            continent:"South America",population:50000
           },{
            continent:"Africa",population:60000
           },{
            continent:"Europe",]
    
    
   //put here the indexes that you want to remove
   var indxRemov = [0,2,3,4];
        
     var len = indxRemov.length;
        
     Object.values(arr).forEach( (val,indx) => {
            
        //get length of indexes array in order to stop when we have removed all the indexes from the original array
            if( len > indx){
           
               //console.log("index: "+indx+" Length: "+indxRemov.length);
               
               //console.log("Remove index: "+indxRemov[0]);
               
               //console.log(indxRemov);
               
         //each time that removes a sub array from the array the length of the original array decreases
               arr.splice(indxRemov[0],1);
               
         //remove from index array the removed index
               indxRemov = indxRemov.filter(item => item !== indxRemov[0]);
               
         //decrease the values of indexes because the original array decreases as well.
               indxRemov = indxRemov.map(x => x-1);
               
             }  

               
     });
        
    console.log(arr);

,

这会为您带来预期的结果

 this.crossCountries = this.api.getCrossCountries();
this.crossCountries.forEach(item => {
    item.response.shift();
    item.response.splice(1,3);
});

console.log(this.crossCountries);

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...