1

I have this function which creates a table based on the values of an object.

function buildTable (){
    //build header
    var header = "<tr><th>USERS</th>"
    for(var i=0; i<groups.length; i++){
        header += "<th>"+groups[i]+"</th>";
    }
    header += "</tr>";

    $("#taxonomy thead").append($(header));
    //build table body
    for(var user in userGroupTable){
        var i = 0; i++;
        var row ="<tr><td>" + usersName[i] + "</td>";
        for(var i=0; i<groups.length; i++){
            var groupName = groups[i];
            var $td = "<td>"+userGroupTable[user][groupName]+"</td>";
            row +=$td;
        }
        row += "</tr>";
        //append the data to the table
        $("#taxonomy tbody").append($(row));

    }
}

I'm trying to iterate between the values in the usersName array but the way it's set up the var i get's reset to 0 on every loop so the same name keeps showing up. I'm not familiar with the for( var x in array), if there some sort of counter within this I can use to iterate through my array? Or should I just set a global variable?

Sorry if the title is poor.

Batman
  • 5,563
  • 18
  • 79
  • 155
  • Try initialising `var i=0` outside of the loop? (And use a different variable, like `j`, for the inner loop) – Bergi Oct 22 '13 at 17:52
  • 1
    [You should not use `for in` loops with arrays at all](http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea) – Bergi Oct 22 '13 at 17:53
  • Oh sorry, userGroupTable is an object – Batman Oct 22 '13 at 17:57
  • But yea you guys are right. I created the variable outside the loop and called it userIndex and that fixed things. Thanks – Batman Oct 22 '13 at 18:03

2 Answers2

1

You are using var i twice. Change one to a more meaningful variable name, like userIndex.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

Initialize i before for loop, and inside for loop you are initializing i with 0, change that to other than i

function buildTable (){
    //build header
    var header = "<tr><th>USERS</th>"
    for(var i=0; i<groups.length; i++){
        header += "<th>"+groups[i]+"</th>";
    }
    header += "</tr>";

    $("#taxonomy thead").append($(header));
    //build table body
        var i = 0;
    for(var user in userGroupTable){
      i++;
        var row ="<tr><td>" + usersName[i] + "</td>";
        for(var j=0; j<groups.length; j++){
            var groupName = groups[j];
            var $td = "<td>"+userGroupTable[user][groupName]+"</td>";
            row +=$td;
        }
        row += "</tr>";
        //append the data to the table
        $("#taxonomy tbody").append($(row));

    }
}
Ramesh Kotha
  • 8,266
  • 17
  • 66
  • 90