1

我正在尝试基于对象的平面数组在 javascript 中创建一个动态的 3 维数组。遍历数组后,数组似乎是空的。如果我在循环中打印,它似乎可以工作,但它似乎已经消失了,我想将它返回给调用者。帮助 ?

//init the 3d array ??
this.teams = [];
for(var i = 0; i < sportsStandings.length; i++) {
  var item = sportsStandings[i];
  if(!this.teams[item.league]) 
    this.teams[item.league] = new Array();

  if(!this.teams[item.league][item.division])
    this.teams[item.league][item.division] = new Array();

  this.teams[item.league][item.division][this.teams[item.league][item.division].length] 
    = new Team(item.teamName, item.wins, item.losses);

  console.log(this.teams); //this prints properly, and i see the 3d array grow
}
console.log('second' + this.teams); //this prints nothing
4

1 回答 1

0

I cleaned up the code a bit, there is a couple of other ways to write it.

this.teams = [];
var teams = this.teams;
for(var i = 0; i < sportsStandings.length; i++) {

    var ss = sportsStandings[i],
        league = ss.league,
        division = ss.division,
        teamName = ss.teamName,
        wins = ss.wins,
        losses = ss.losses;

    if (!teams[league]) {
        teams[league] = {};
        teams[league][division] = [];
    } else if (!teams[league][division]) {
        teams[league][division] = [];
    }

    var newTeam = new Team(teamName, wins, losses);
    teams[league][division].push(newTeam);
}
于 2012-04-30T19:39:59.497 回答