我需要按顺序添加数组的元素,非常类似于[How can I add each element of one array to another one's corresponding element using a ParallelStream?的问题,但我使用的是javascript和angular。我的数组可以包含任意数量的元素,最多可达31天(天),但它们在每个数据对象中的元素数量始终相同。
$scope.test31days = {
"change_series": [
{ "data": [0,0,0,2,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,2,0,0],
"name": "EMERGENCY",
"color": "#904040"},
{ "data": [0,1,3,0,0,0,0,1,2,3,3,0,0,0,2,1,1,1,0,0,1,1,3,3,1,0,0,1,2,2,0],
"name": "MINOR",
"color": "#333"},
{ "data": [0,0,1,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,2,0,0,0,0,0,0],
"name": "MAJOR",
"color": "#666"}
],
"change_title": "CHANGES"
}
我的控制台输出告诉我正确地将元素分开(在某种程度上),但是当我使用if / else if语句运行它时,我崩溃浏览器,所以我知道我搞砸了。< / p>
$scope.getTotalChanges = function(){
var series = $scope.test31days.change_series;
var arry = [];
for(var i = 0; i < series.length; i++){
// console.log('change_series loop #', i);
// console.log('change_series.data length', series[i].data.length);
var seriesData = series[i].data;
// console.log('series[i].name', series[i].name)
// console.log('seriesData', seriesData)
for(var j = 0; j < seriesData.length; j++){
console.log('For inner #', j);
console.log('seriesData #', seriesData[j]);
if (j = 0) {
arry = seriesData;
} else if (j > 0) {
arry[j] += seriesData[j]
};
}
}
// return series;
console.log('arry ', arry);
return arry;
};
我的最终目标是为31(天)
提供单个数据数组答案 0 :(得分:1)
var series = $scope.test31days.change_series;
var dataLength = series[0].data.length;
var result = Array.apply(null, new Array(dataLength)).map(Number.prototype.valueOf,0); //initialize result array with zeros
for(var i = 0; i < series.length; i++) {
for(var j = 0; j < dataLength; j++) {
result[j] += series[i].data[j];
}
}