将表行加载到数组数组

时间:2018-08-27 20:28:55

标签: javascript jquery

我正在制作这个演示。如何将表的每一行导出到数组内部的数组中?

我需要类似

的输出
arrayofArray = [
                 [49, 16, 135,  32, 53],
                 [51, 16, 140,  34, 55],
                 [66, 12' 140,  36, 50]
]

var length =  $('table tbody tr').length;   
var arrayofArrays =[];
for (var i = 0; i < length; i++) { 
   arrayofArrays.push(parseInt($('table tbody tr:eq('+i+') td').text().trim()))
} 

console.log(arrayofArrays);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
	<tbody>
		 <tr>
				<td align="center"> 49 </td>
				<td align="center"> 16 </td>
				<td align="center"> 135 </td>
				<td align="center"> 32 </td>
				<td align="center"> 53 </td>
		 </tr>
		 <tr>
				<td align="center"> 51 </td>
				<td align="center"> 16 </td>
				<td align="center"> 140 </td>
				<td align="center"> 34 </td>
				<td align="center"> 55 </td>
		 </tr>
		 <tr>
				<td align="center"> 66 </td>
				<td align="center"> 12 </td>
				<td align="center"> 140 </td>
				<td align="center"> 36 </td>
				<td align="center"> 50 </td>
		 </tr>
	</tbody>
</table>

2 个答案:

答案 0 :(得分:2)

let arrayOfArrays = [];

//You can iterate each table row of the table body like so
$('table tbody tr').each(function(){
    //Declare a new array object to hold all cell values for this row
    let newArray = [];
    //Iterate each table cell of the row, currently this refers to the table row
    $(this).find('td').each(function(){
         newArray.push(parseInt($(this).text()));
    });
    //Push row array into main array
    arrayOfArrays.push(newArray);
});

答案 1 :(得分:0)

这是VanillaJs版本。

let table = document.querySelector("table"),
    tBody = table.tBodies[0];

console.log(
  Array.from(tBody.rows)
    .map(row => Array.from(row.cells)
      .map(cell => cell.innerText * 1))
);
<table>
  <tbody>
    <tr>
      <td align="center"> 49 </td>
      <td align="center"> 16 </td>
      <td align="center"> 135 </td>
      <td align="center"> 32 </td>
      <td align="center"> 53 </td>
    </tr>
    <tr>
      <td align="center"> 51 </td>
      <td align="center"> 16 </td>
      <td align="center"> 140 </td>
      <td align="center"> 34 </td>
      <td align="center"> 55 </td>
    </tr>
    <tr>
      <td align="center"> 66 </td>
      <td align="center"> 12 </td>
      <td align="center"> 140 </td>
      <td align="center"> 36 </td>
      <td align="center"> 50 </td>
    </tr>
  </tbody>
</table>