我正在创建一个小型系统(供个人使用),以便分析一些学校标记。 在Html页面( index.html )中,我想插入一个JavaScript脚本来计算同一主题的 mydata.js 值的平均值并将它们放入进入 index.html 页面中的表格。
mydata.js 看起来像这样:
myData([
{"subject": 1, "value": 5},
{"subject": 2, "value": 4},
{"subject": 3, "value": 7},
{"subject": 1, "value": 5},
{"subject": 2, "value": 7},
{"subject": 3, "value": 6},
{"subject": 2, "value": 3}
]);
index.html 如下所示:
<html>
<head>
<title>index</title>
</head>
<body>
<table>
<tr>
<td>SUBJECT: 1</td>
<td>AVERAGE: x</td> <!-- Instead of x should be 5 -->
</tr>
<tr>
<td>SUBJECT: 2</td>
<td>AVERAGE: y</td> <!-- Instead of y should be 4.6 -->
</tr>
<tr>
<td>SUBJECT: 3</td>
<td>AVERAGE: z</td> <!-- Instead of z should be 6.5 -->
</tr>
</table>
<script src="path/mydata.js"></script>
</body>
</html>
非常感谢!
答案 0 :(得分:0)
下面给出的是我用过的JS的相关部分
for (var i = 0; i < myData.length; i++) {
if (myData[i].subject == '1') {
avg1 = avg1 + myData[i].value;
count1++;
} else if (myData[i].subject == '2') {
avg2 = avg2 + myData[i].value;
count2++;
} else if (myData[i].subject == '3') {
avg3 = avg3 + myData[i].value;
count3++;
}
}
document.getElementById('avg_sub1').innerHTML = avg1 / count1;
document.getElementById('avg_sub2').innerHTML = avg2 / count2;
document.getElementById('avg_sub3').innerHTML = avg3 / count3;
答案 1 :(得分:0)
这是一个简单的伪解决方案。
<script>
var data = [
{ "subject": 1, "value": 5 },
{ "subject": 2, "value": 4 },
{ "subject": 3, "value": 7 },
{ "subject": 1, "value": 5 },
{ "subject": 2, "value": 7 },
{ "subject": 3, "value": 6 },
{ "subject": 2, "value": 3 }
];
var averageArray = [];
for (var i = 0 ; i < data.length ; i++) {
var average = data[i].value;
for (var j = 0 ; j < data.length; j++) {
if (data[i].subject == data[j].subject) {
average = (average + data[j].value) / 2;
}
}
averageArray.push(average);
}
</script>
现在,您的averageArray
将包含[5,4.6,6.5.....]
使用此按钮显示在视图上。
答案 2 :(得分:0)
您可以使用某些库来执行此操作。
E.g underscore
var myData =[
{"subject": "mmm", "value": 5},
{"subject": "bbb", "value": 4},
{"subject": "ccc", "value": 7},
{"subject": "mmm", "value": 5},
{"subject": "bbb", "value": 7},
{"subject": "ccc", "value": 6},
{"subject": "bbb", "value": 3}
];
var tr = '';
var subjects = _.groupBy(myData, "subject");
for (var sub in subjects) {
var s = _.pluck(subjects[sub], 'value');
var avg = _.reduce(s, function(a, b) {
return a + b;
}, 0) / (s.length === 0 ? 1 : s.length);
tr += '<tr><td>'+sub+'</td><td>'+avg+'</td></tr>';
}
document.getElementById("t").innerHTML = tr;