我需要将数组转换为按时间排序的html表,添加排名并计算第一个地方的时间损失。 数组示例:`
var array = [
["McNulty Oscar", "USA", "108:45.1"],
["Johansson Anton", "SWE", "87:48.9"],
["Schneider Florian", "SUI", "dns"],
["Rio Nicolas", "FRA", "57:45.1"]
];`
最终的HTML表应如下所示:
1 Rio Nicolas FRA 57:45.1
2 Johansson Anton SWE 87:55.9 30:10.8
3 McNulty Oscar USA 107:45.2 51:03.1
Schneider Florian SUI dns dns
我的想法是如何在 Jquery 转换数组转换为 HTML表,然后使用 tablesorter 插件。我还不知道何时以及如何计算时间损失。这是好方法还是我完全出去了?
答案 0 :(得分:1)
遗憾的是,没有简单的解决方案。您正在处理的值既不是时间值(就JS而言......请参阅JS Date
对象以获取更多时间信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date),也不是它们可以编号的数字直接减去,无需操纵。
最好的办法是将值拆分并以长时间的方式进行减法。 。 。使用var timeElements[2] = each.split(".")
获取每个值的分钟/秒/十分之一秒的数组。此时,您可以:
第二个选项可能是更容易理解的逻辑,即使它有很多步骤。
如果没有时差,还有其他选择。 。 。如果你可以将零添加到所有时间值,那么每分钟,秒和十分之一的字符总是具有相同的字符数, AND “dns”是唯一会发生的其他值,除了时间之外,字符串的直接<
比较仍然实际上可用于排序,因为在字符串上使用大于/小于的工作方式。例如:
这真的不是一种最佳方法。 。 。抛弃这种字符串比较并不需要太多。 。 。但是,如果你能够非常肯定你所获得的价值,那么它仍然值得一提。
。 。 。如果你可以跳过整个“时差”的一部分。 :d
答案 1 :(得分:0)
我使用this demo和tablesorter将tablesorter build table widget放在一起。
HTML
<div id="result"></div>
脚本
$(function () {
var array = [
["Name", "Country", "Time", "Diff"],
["McNulty Oscar", "USA", "108:45.1", ""],
["Johansson Anton", "SWE", "87:48.9", ""],
["Schneider Florian", "SUI", "dns", ""],
["Rio Nicolas", "FRA", "57:45.1", ""]
],
// time column (zero-based index)
timeColumn = 3,
diffColumn = 4,
// convert min:sec.ms => sec.ms
convertTime = function (time) {
var val;
if (time && /:/.test(time)) {
val = time.split(':');
return parseFloat(val[0] || 0) * 60 + parseFloat(val[1] || 0);
} else {
return Number.POSITIVE_INFINITY;
}
},
// convert sec.ms => min:sec.ms
formatTime = function (time) {
var minutes = parseInt(time / 60);
return minutes + ':' + (time - (minutes * 60)).toFixed(1);
},
calculateDiff = function (table) {
var $tds, minTime,
$table = $(table),
$trs = $table.children('tbody').children(),
times = [];
$trs.each(function () {
$tds = $(this).children();
times.push(convertTime($tds.eq(timeColumn).text()));
});
minTime = Math.min.apply(Math, times);
$trs.each(function (i) {
var diff = times[i] - minTime,
result = times[i] === Number.POSITIVE_INFINITY ? 'dns' :
diff === 0 ? '' : formatTime(diff);
$(this).children()
.eq(0).html(result !== 'dns' ? i + 1 : '').end()
.eq(diffColumn).html(result);
})
.trigger('update');
};
$('#result').tablesorter({
theme: 'blue',
emptyTo: 'zero',
widgets: ['zebra', 'build'],
sortList: [[3, 0]],
widgetOptions: {
build_source: array,
build_footers: {
rows: 0
},
build_numbers: {
// include row numbering column?
addColumn: "Rank",
// make column sortable?
sortable: true
}
},
initialized: function (table) {
calculateDiff(table);
}
});
});
更新:修改后的代码和demo以包含排名列和排序。