我有这样的数据:
A,10,USA
B,20,UK
A,5,USA
输出必须是这样的:
A has ran 15 miles with average of 7.5
B has ran 20 miles with average of 20
在 jQuery 中我写了这样的代码:
$(document).ready(function(){
$('#calculate').click(function(){
$('#report').empty();
var data = $('#input').val();
$.each($.csv.toArrays(data), function(_, row) {
var namecount = 0
$(row[0]).each(function(){
namecount++;
});
var totalevents = 0;
$(row[1]).each(function(){
totalmiles++;
});
var average = totalmiles / namecount;
$('#report').append('<div>' + row[0] + ' has ran ' + totalmiles +" "+'miles with an average of'+" "+average +'</div>');
});
});
});
但代码对总里程和平均值计算 0 和 NaN。我尝试在 jQuery 中使用 Hashtable 来解决这个问题,但我还没有找到一个好的指南来向我展示如何通过 javascript 或 jQuery 来进行这些计算。
最佳答案
尝试将此作为您的主要代码:
var aggregates = {};
$.each($.csv.toArrays(data), function(_, row) {
var id = row[0];
var miles = row[1];
if (aggregates[id] === undefined) {
aggregates[id] = {
count : 0,
miles : 0
};
}
aggregates[id].miles += parseInt(miles);
aggregates[id].count++;
});
for (id in aggregates) {
$("#report").append(id + " ran " + aggregates[id].miles + " miles with average of " + (aggregates[id].miles / aggregates[id].count));
}
这是它的 fiddle : http://jsfiddle.net/7Ev7V/
这里,聚合对象充当哈希表,以 id 作为键,对象将计数和英里作为值。
关于javascript - 使用 Java Script 或 jQuery 对特定项目进行计数并创建 HashMap ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15486330/