嵌套循环-对象和数组中字符串的输出顺序

时间:2018-12-07 13:03:40

标签: javascript jquery arrays class object

我只是想不通这一点。所以,我有班级团队和班级球员。玩家对象存储在其团队(对象)中。

团队本身存储在listofteams对象中。

每次创建团队或球员时,我都希望javascript在列表中循环并向每个团队及其球员追加。例如:

团队1- 玩家1- 玩家2

团队2- 玩家3

不幸的是,当前输出看起来像这样:

团队1- 玩家1- 玩家2- 玩家3

团队2- 玩家3属于团队2,但显示在团队1下。

我如何设法遍历我的对象和数组,以便将玩家附加到他们实际所属的团队之下?

以下是课程:

 class Team {
     constructor(teamname, teamleague ) {
         this.teamname = teamname;
         this.teamleague = teamleague;
         this.players = [];
         this._id = this.generateid();
     }
     generateid() {
         return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
           var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
           return v.toString(16);
         });
       }

 };

 class Player {
     constructor (playerteam, playerfirstname, playerlastname, playernumber) {
     this.playerteam = playerteam;
     this.playerfirstname = playerfirstname;
     this.playerlastname = playerlastname;
     this.playernumber = playernumber;
     this.team_id = $('#select-native-2 option:selected').attr("id");
     }
 };

这是我的循环:

function writeall () {
    $("#teamappendarea").empty();

    for(element in listOfTeams){ 
        $("#teamappendarea").append("<p>" + listOfTeams[element].teamname + "</p>");
            for (var i = 0; i < listOfTeams[element].players.length; i++){

                $("#teamappendarea").append("<p>" + listOfTeams[element].players[i].playerlastname + "</p>");
            }
        } 
};

团队展示的console.log

{
  "981929ef-c918-4e59-9296-49581bcba144": {
    "teamname": "team1",
    "teamleague": "",
    "players": [{
      "playerteam": "team1",
      "playerfirstname": "Player1",
      "playerlastname": "Player1",
      "playernumber": "1111",
      "team_id": "981929ef-c918-4e59-9296-49581bcba144"
    }, {
      "playerteam": "team2",
      "playerfirstname": "Player2",
      "playerlastname": "Player2",
      "playernumber": "1111",
      "team_id": "7d2ab469-a33a-4246-94d1-fdc98886f0c1"
    }],
    "_id": "981929ef-c918-4e59-9296-49581bcba144"
  },
  "7d2ab469-a33a-4246-94d1-fdc98886f0c1": {
    "teamname": "team2",
    "teamleague": "",
    "players": [],
    "_id": "7d2ab469-a33a-4246-94d1-fdc98886f0c1"
  }
}

0 个答案:

没有答案