0

I am trying to loop through a table's td and update each td based on an array:

var person = []; //each array stores a person's name, height, and weight

for (i = 0; i < 5; i++) {

  $("table th").each(function(){
    $(this).text(person[i].name);
  });

  $("table td").each(function() {
    $(this).text(person[i].height + '/' + person[i].weight);
  });

}

However, this ends up storing the last value of the array in the td... I need help in looping through the td's based on their index... can someone help?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Trung Tran
  • 13,141
  • 42
  • 113
  • 200

1 Answers1

2

The problems is that you are iterating over the th/td, so, every time it iterate the first for loop, then with jQuery you iterate all th/td and update the content with the current index of the outer for value. Don't know if you understand all that but i will give you an example of how to solved.

var person = []; //each array stores a person's name, height, and weight

for (i = 0; i < 5; i++) {
  $("table th:eq("+i+")").text(person[i].name);
  $("table td:eq("+i+")").text(person[i].height + '/' + person[i].weight);
}

I don't know what is your expected final result, but the code i wrote get exactly the th/td at the same index you are currently iterating over.

Or, if you are sure you have the same amount of td/th that exist in your array, probably this is ok for you

$("table th").each(function(index){
  $(this).text(person[index].name);
});

but it can fail in a few ways depending on the content of the person array

hope it help

Castro Roy
  • 7,623
  • 13
  • 63
  • 97