2

I'm working on a statistics view via Angular-Chart for a shoppinglist-App. It should show a graph of all spended costs by every user for a year. Now this is how I generate the JSON for the Chart:

$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);
    };

The output in the console looks like this:

[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]

The array is filled fine but the push statement :

$scope.data.data.push({x:months[i],y: usercosts});

just dont work right. "usercosts" is in every line the same value.... the last one; in this case 0. Although I push before I go through the next month. I dont now what to do anymore and would appreciate to get some smart answers from you. best wishes Christoph

4

1 回答 1

0

需要了解,当您将数组推送到 chartData 数组时,它usercosts不是该数组的副本。usercostsreference

然后当你设置:

 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
于 2015-07-16T13:39:47.167 回答