1

I'm trying to create a 3 dimensional array dynamicall in javascript based on a flat array of objects. after looping through the array, the array seems empty. If I print while in the loop, it seems to work, but then it seems to be gone and I want to return this to the caller. Help ?

//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 に答える