Store table in 2d array jquery

戏子无情 提交于 2019-12-11 04:31:39

问题


I'm trying to store a table in a 2d array so that each item in the array will be an array containing all the cells in a row.

I'm using:

var tRow = [];
var tRows = [];
tab = document.getElementById('table'); 

for(var r = 0 ; r < tab.rows.length ; r++) {
    for (var c=0; c < tab.rows[r].cells.length; c++){
        tRow[c] = tab.rows[r].cells[c].innerHTML;                       
    }

    tRows.push(tRow);
}

this just gives me the last row item in 20 places rather than each item in the table at its respective index. So, for this table:

<tr> 
 <td>Row 1 cell 1</td>
 <td>Row 1 cell 2</td>
 <td>Row 1 cell 3</td>
 <td>Row 1 cell 4</td>
</tr>
<tr>
 <td>Row 2 cell 1</td>
 <td>Row 2 cell 2</td>
 <td>Row 2 cell 3</td>
 <td>Row 2 cell 4</td>
</tr>

tRows will be:

tRows =[ [Row 2 cell 1,Row 2 cell 2,Row 2 cell 3,Row 2 cell 4] , [Row 2 cell 1,Row 2 cell 2,Row 2 cell 3,Row 2 cell 4] ]

instead of:

tRows =[ [Row 1 cell 1,Row 1 cell 2,Row 1 cell 3,Row 1 cell 4] , [Row 2 cell 1,Row 2 cell 2,Row 2 cell 3,Row 2 cell 4] ]

I don't know what I'm doing wrong. Please help.


回答1:


You can do this with two map() functions.

var tRows = $('tr').map(function() {
  return [$(this).find('td').map(function() {
    return $(this).text()
  }).get()]
}).get()

console.log(tRows)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>Row 1 cell 1</td>
    <td>Row 1 cell 2</td>
    <td>Row 1 cell 3</td>
    <td>Row 1 cell 4</td>
  </tr>
  <tr>
    <td>Row 2 cell 1</td>
    <td>Row 2 cell 2</td>
    <td>Row 2 cell 3</td>
    <td>Row 2 cell 4</td>
  </tr>
</table>



回答2:


Your issue is you need a new tRow array for each iteration of outer loop.

Just move var tRow = []; inside that row loop

var tRows = [];
tab = document.getElementById('table');

for (var r = 0; r < tab.rows.length; r++) {
  var tRow = [];// start new row array
  for (var c = 0; c < tab.rows[r].cells.length; c++) {
    tRow[c] = tab.rows[r].cells[c].innerHTML;       
  }
  tRows.push(tRow);
}

console.log(tRows);
<table id="table">
  <tr>
    <td>Row 1 cell 1</td>
    <td>Row 1 cell 2</td>
    <td>Row 1 cell 3</td>
    <td>Row 1 cell 4</td>
  </tr>
  <tr>
    <td>Row 2 cell 1</td>
    <td>Row 2 cell 2</td>
    <td>Row 2 cell 3</td>
    <td>Row 2 cell 4</td>
  </tr>
</table>


来源:https://stackoverflow.com/questions/41924041/store-table-in-2d-array-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!