【问题标题】:Convert table to multidimensional array将表转换为多维数组
【发布时间】:2012-05-25 14:44:37
【问题描述】:

我有点像 JavaScript 菜鸟,所以解决这个问题的方法可能比我想象的更基本。我正在尝试从该表中获取数据并将其显示在数组中。表格开头如下:

<table id="myTable">
     <col>
        <thead>
             <tr>
                <th>Date</th>
                <th>Results1</th>
                <th>Results2</th>
            </tr>
         </thead>
         <tbody>
             <tr>
                <td>Jan-00</td>
                <td>9</td>
                    <td>10</td>
             </tr>
             <tr>
                <td>Feb-00</td>
                <td>92</td>
                <td>64</td>
             </tr>

然后从那里继续(这是一张有很多&lt;tr&gt; 的长桌)。

我获取变量的代码如下所示(向其他资源提供帮助以帮助我解决此问题):

var columns = $('#myTable thead th').map(function() {
        return $(this).text();
    });
    var tableObject = $('#myTable tr').map(function(i) {
        var row = {};
        // Find all of the table cells on this row.
        $(this).find('td').each(function(i) {
        // Determine the cell's column name by comparing its index
        //  within the row with the columns list we built previously.
        var rowName = columns[i];
        // Add a new property to the row object, using this cell's
        //  column name as the key and the cell's text as the value.
            row[rowName] = $(this).text();
        });
        // Return the row's object representation, to be included
        //  in the array that $.map() ultimately returns.
        return row;
        // .get() to convert the jQuery set to a regular array.
        }).get();
        for (var i in tableObject) {
            $.each(tableObject[i], function(key,value) { 
                var line1 = {};
                line1[key] = value;
                console.log(line1); //test
            });
        }

在 console.log 测试中,变量 line1 现在显示其持有的键和值,如下所示:Date: Jan 00, Results1:9, Results2:10。

这一切都很好,但我确实需要将这些值按以下格式放入一个新数组中:

var new = [[Date, Results1], [Date, Results2], etc...];

抱歉,如果我重复一个问题,但找不到我想要的东西。非常感谢任何人可以提供的任何帮助。

【问题讨论】:

  • 不要使用for...in 来遍历数组,也没有必要在该循环内使用$.each()

标签: javascript jquery arrays html-table


【解决方案1】:

应该这样做:

var ary = [];
$('tr').each(function() {
    date = $('td:first', this).text();
    $('td:gt(0)', this).each(function() {
        ary.push([date, $(this).text()]);
    });
});

【讨论】:

  • 谢谢!这行得通,尽管我仍在解开它的工作原理。非常感谢您的帮助。
  • 基本上它遍历表格行,将第一个单元格的值存储为日期,然后遍历行中剩余的单元格,将日期/值对添加到数组中。
【解决方案2】:

看看http://www.w3schools.com/jsref/dom_obj_table.asp 我建议使用 tableObject.rows 来获取包含单元格的行数组。然后使用 rows.cells 获取所有单元格元素。 它可能看起来像

   var table =document.getElementById("myTable")
  var foo = new array(table.rows.length);
  for(var j =0; j<foo.length; j++)
   foo[j]=foo[j].cells;

这会将表格放入一个名为 foo 的二维数组中。以形式表示 foo[rowindex][col/cellindex] (即 foo[0][1] 将返回结果 1;

希望这能让你开始

【讨论】:

  • 感谢绿巨人。我也会将此视为一种可能更有效的解决方案。
猜你喜欢
  • 2014-06-28
  • 1970-01-01
  • 2023-03-26
  • 2019-06-29
  • 2012-08-15
  • 2015-08-18
相关资源
最近更新 更多