【发布时间】: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>
然后从那里继续(这是一张有很多<tr> 的长桌)。
我获取变量的代码如下所示(向其他资源提供帮助以帮助我解决此问题):
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