2015-05-20 102 views
4

嗨它接縫,我不能推我的數組? 代碼:無法讀取屬性'推'未定義的Javascript

$scope.arrResult = []; 
    dpd.timesheets.get(function (result) { 
    console.log(result); 

    for (i = 0, n = result.length; i < n; i++) { 
     var item = result[i]; 
     $scope.arrResult[item.week].push(item); 
    } 
    console.log($scope.arrResult); 

    }); 

我得到這個控制檯錯誤

Uncaught TypeError: Cannot read property 'push' of undefined 

如果我設置$scope.arrResult[item.week].push(item); to $scope.arrResult[item.week] = item; 它的工作原理,並沒有錯誤 但我需要/想推,什麼是錯?

回答

9

這是因爲

$scope.arrResult[item.week] 

本身不是一個數組。

push()Array.prototype

要明白我的意思,儘量

$scope.arrResult[item.week] = []; 

$scope.arrResult[item.week] = new Array(); 

,然後嘗試push()

+0

我明白了,嗯..但是怎麼辦我這樣做是正確的方式,如果我設置= []推前,我的理由t在數組中獲得一個對象,並且我想要所有:) – Stweet

+0

@Stweet,你是​​什麼意思'all'。也許甚至不需要數組? – AmmarCSE

+0

結果包含很多對象,我想在$ scope.arrResult [week] 例如。 $ scope.arrResult [21]包含第21周的所有對象 – Stweet

相關問題