2016-03-22 46 views
0

認爲這是一些數據,我想在我的AngularJS視圖發佈(荷蘭語):計算子對象的價值觀和對父母表現出

$scope.data = 
    [ 
     { 
      name: "actief", 
      value: null, 
      children: 
      [ 
       { 
        name: "vast actief", 
        value: [20, 30, 40, 50], 
        children: null 
       }, 
       { 
        name: "vlottend actief", 
        value: [215, 230, 245, 500], 
        children: null 
       }, 
       { 
        name: "bewegend actief", 
        value: [134, 135, 136, 137], 
        children: null 
       } 
      ] 
     }, 
     { 
      name: "stilstaand", 
      value: null, 
      children: 
      [ 
       { 
        name: "vast stilstaand", 
        value: [2000, 3000, 4000, 5000], 
        children: null 
       }, 
       { 
        name: "vlottend stilstaand", 
        value: [2150, 2300, 2450, 5000], 
        children: null 
       }, 
       { 
        name: "bewegend stilstaand", 
        value: [1340, 1350, 1360, 1370], 
        children: null 
       } 
      ] 
     } 
    ]; 

要在我看來,我可以做一個列表發佈此對象是這樣的:

<ul ng-repeat="item in data"> 
    <li>{{item.name}}</li> 
    <ul ng-repeat="child in item.children"> 
     <li>{{ child.name }}</li> 
     <ul ng-repeat="value in child.value"> 
      <li>{{ value }}</li> 
     </ul> 
    </ul> 
</ul> 

我希望我的父對象{{ item name }}有一個與孩子如之和的數組第一父將有此數組:[369, 395, 421, 687]

我試圖做我的控制器內的這種計算(我知道,在控制器中沒有邏輯,但它只是用於測試)

for (var i = 0; i < $scope.data.length; i++){ 
    $scope.data[i].value = []; 
    for (var j = 0; j < $scope.data[i].children.length; j++) { 
     if ($scope.data[i].children[j].value.length > 0) { 
      for (var k = 0; k < $scope.data[i].children[j].value.length; k++) { 
       console.log(typeof $scope.data[i].children[j].value[k]); // says number! 
       $scope.data[i].value[k] += $scope.data[i].children[j].value[k]; // But my array is NAN??? 
      } 
     } 
    } 
} 

中有4個位置我父值數組,但其中的al是NaN,我做錯了什麼?

邊問

,因爲我做在我看來,循環,不存在計算陣列位置出現的總計更短的方法是什麼?

回答

0

這句法

$scope.data[i].value[k] += ... // some value 

假定已經存在於數組的k位置增量的值。

在你的代碼中,數組最初是空的。正在發生的事情是這樣的:要解決這個問題

var myArray = []; 
myArray[0] += 1; // error: there is no element at the 0 position! 

一種方法是空數組零個值初始化:

$scope.data[i].value = [0, 0, 0, 0]; // you can also seed the initial zeroes using a loop 
+0

你能肯定嗎?因爲當我做'var myArray = []; myArray + = 5'我剛剛拿到'5'。但是當我做'var myArray = []; myArray + = 5; myArray + = 10'我得到'510'。我看到的是它不會計數數字,而是將它們連接起來。 – Peter

+1

從我對你的問題的理解中,你想要做的是在數組中增加一個值,該數組的語法爲'myArray [index] + = value'。所以如果你有'var myArray = [1,2,3]',並且你想把'5'加到第一個元素上,你可以使用'myArray [0] + = 5'。注意使用索引'0'。沒有索引的語法('myArray + = 5')在這種情況下並不是你想要的。 –

+0

你是對的,我正在等待,直到我可以編輯我以前的答案,因爲我已經注意到了!我們會成功的,非常感謝你! – Peter