如果您只想要一个数字,它是两个数组组合的平均值,请尝试以下操作:
var one = [0,20,30,40];
var two = [43,20,10,50];
var i, j;
var average = 0;
for(i = 0; i < one.length; i++){
average += one[i];
}
for(j = 0; j < two.length; j++){ // (two arrays for flexibility.)
average += two[j];
}
console.log(average /= (i+j));
// 26.625
如果你想要数组的平均值,在特定索引处,试试这个:
var one = [0,20,30,40];
var two = [43,20,10,50];
var i;
var average = [];
for(i = 0; i < one.length; i++){
average.push((one[i] + two[i]) / 2);
}
console.log(average);
// [21.5, 20, 20, 45]
编辑:
根据我对您的编辑的了解,您希望将平均百分比添加到one
, 以获得two
. 这应该有效:
var i, n = 0;
var average = 0;
var one = [0,20,30,40] ;
var two = [0,60,70,120] ;
for(i = 0; i < one.length; i++){
if(one[i] != 0){
average += two[i] / one[i];
n++;
}
}
average = (average / n - 1)*100;