首页 > 解决方案 > Angular如何从另一个数组填充数组

问题描述

我有一个名为我的游戏的数组它有很多属性,例如游戏类型我想根据属性游戏类型填充一些三个其他数组,但它不起作用这是我的游戏数组的一个示例

hideScore: true, started: true, startedAt: "Fri, 02 Jul 2021 09:04:25 GMT", finished: true, finishedAt: "Fri, 20 Aug 2021 15:35:37 GMT", …}
archived: false
bgGame: "#1a1f29"
client: "client test"
company: "tunisia"
country: "Tunisia"
createdAt: "2021-07-02T09:03:34.015Z"
finished: true
finishedAt: "Fri, 20 Aug 2021 15:35:37 GMT"
gameType: "test"
hideScore: true
id: "60ded6668734e65c51f50996"
language: "English"
maxLevel1: 10.47195
maxLevel2: 2.065616666666668
maxScore: 23400
name: "game test"
nbrDoors: 8
nbrPlayersPerTeam: 8
partner: "khouloud ben khssib"
playtime: 30
started: true
startedAt: "Fri, 02 Jul 2021 09:04:25 GMT"
startsAt: "Fri, 02 Jul 2021 09:03:00 GMT"
teams: (20) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
teamsCount: 20
textColor: "#ffffff"
updatedAt: "2021-08-20T15:35:37.348Z"
user: "609321b935e3f04d04d44337"
__v: 0
_id: "60ded6668734e65c51f50996"

我有三个名为 gametype 的数组

NumberofLive: any[] =[];
  NumberofTest: any[] =[];
  NumberofDemo: any[] =[];

我想每次都填满一张桌子,我写了这样的东西

for(let i=0;i<this.MyGames.length; i++){
      
      switch(this.MyGames[i].gameType) { 
        case 'test': { 
        
          this.NumberofTest=this.NumberofTest+this.MyGames[i]           
           break; 
        } 
        case 'live': {                  

                          this.NumberofLive=this.NumberofLive+this.MyGames[i]           

           console.log('salzem');     console.log(this.NumberofLive[1].gameType)

           
           break; 
        } 
        default: {              


          this.NumberofDemo=this.NumberofDemo+this.MyGames[i]           
           break; 
        } 
     } 

    }

当我记录我的表时,我发现一些未定义的东西

标签: angulartypescript

解决方案


您不能只添加带有“+”号的数组,您必须将新对象推入其中。

this.NumberofTest.push(this.MyGames[i])

另外,我认为更优雅的解决方案是没有 for 循环的 array.filter 方法,如下所示:

this.NumberofTest = this.MyGames.filter((item) => item.gameType==='test')

推荐阅读