我正在通过Angular-Chart为购物清单-App工作统计视图。 它应该显示每个用户一年所有成本的图表。 现在这就是我为图表生成JSON的方式:
$scope.data = {
series: users,
data: []
};
console.log(chartdata);
$scope.load = function(){
for(var i = 0; i< months.length; i++){
for(var z = 0; z < chartdata.length; z++){
var obj = chartdata[z];
if(obj.year == $scope.dt.getFullYear()){
if(obj.month == months[i]){
for(var t =0; t < users.length;t++){
if(obj.name == users[t]){
usercosts[t] = (usercosts[t] + obj.price);
console.log(obj.price);
console.log(usercosts);
}
}
}
}
}
console.log(usercosts);
$scope.data.data.push({x:months[i],y: usercosts});
for(var p = 0; p < users.length; p++){
usercosts[p]=0;
}
}
console.log($scope.data.data);
};
控制台中的输出如下所示:
[0, 0]
44
[44, 0]
[44, 0]
[0, 0]
[0, 0]
7
[7, 0]
[7, 0]
20
[20, 0]
[20, 0]
5
[5, 0]
[5, 0]
[0, 0]
[0, 0]
[0, 0]
[0, 0]
[0, 0]
数组填充正常,但是push语句:
$scope.data.data.push({x:months[i],y: usercosts});
只是不正常工作。 &#34; usercosts&#34;在每一行都是相同的价值......最后一行;在这种情况下0。 虽然我在下个月经历之前就已经开始了。 我现在不再做什么,并希望从你那里得到一些明智的答案。 最好的祝愿 克里斯托弗
答案 0 :(得分:0)
需要了解的是,当您将usercosts
数组推送到chartData数组时,它不是usercosts
的副本,而是该数组的reference
。
然后在你设置时:
for(var p = 0; p < users.length; p++){
usercosts[p]=0;
}
您正在使用刚推入另一个数组的相同数组引用。
更改将反映在您有参考的任何地方。
很简单的例子:
var a = [1];
var b = a; // looks like it would be a simple copy
alert( b[0] ); // alerts 1
// change value of b[0]
b[0] = 100;
alert( a[0]); // alerts 100 also because a and b are references to same array