2015-05-20 50 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

相关问题