将表存储在2d数组jquery中 [英] Store table in 2d array jquery

查看:150
本文介绍了将表存储在2d数组jquery中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将表存储在2d数组中,以便数组中的每个项都是包含一行中所有单元格的数组。

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.

我正在使用:

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);
}

这只是给了我20个地方的最后一个行项目而不是每个项目表格各自的索引。因此,对于此表:

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将是:

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] ]

而不是:

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.

推荐答案

你可以用两个 map()来做到这一点函数。

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>

这篇关于将表存储在2d数组jquery中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆