我想在不使用属性名称的情况下计算下面提到的最内层数组的平均值。有出路吗。我正在使用javascript。目前使用这种语法,我得到的数组没有定义。
average.js
var data=
[
{
"load":[1,2,3],
"network":[5,6,7]
},
{
"load":[10,11,12],
"network":[14,15,16]
}
]
// I want to calculate the average for each of the properties 'load','network' and many more....
function avg(i)
{
for(j=0;j<data[i].length;j++)
{
sum=0;
for(k=0;j<data[i][j].length;k++)
{
sum+=data[i][j][k];// it do not seems correct
}
average=sum/3;
document.write("value "+i+":"+average);//just for testing
}
}
average.html
<!DOCTYPE html>
<meta charset="utf-8">
<head>
<script src="average.js"></script>
</head>
<body>
<script>
avg();
</script>
</body>
</html>
答案 0 :(得分:0)
试试这个
function avg(i)
{
for(j in data[i])
{
sum=0;
for(k=0;k<data[i][j].length;k++)
{
sum+=data[i][j][k];
}
average=sum/3;
document.write("value "+i+":"+average);
}
}
像这样称呼
<script>
avg(0); // Index
</script>
工作小提琴DEMO