TypeError:无法读取未定义的属性“push”

时间:2014-04-17 10:54:37

标签: javascript angularjs angularjs-scope

我正在尝试将'currentBall'对象推入'currentOver.balls'数组

$scope.currentOver.balls.push($scope.currentBall);

运行上述代码之前的两个对象的当前状态(来自开发工具):

$scope.currentOver: Array[1]
0: Object
balls: Array[0]
bowlerId: 0
byes: 0
legByes: 0
noBalls: 0
runs: 0
wickets: 0
wides: 0
__proto__: Object
length: 1
overId: 1
__proto__: Array[0]

$scope.currentBall: Object
ballId: 0
batsmanId: 0
bowlerId: 0
byes: 0
legByes: 0
noBalls: 0
runs: 2
wicketsNumber: 0
wicketsType: 0
wides: 0
__proto__: Object

我收到错误:Cannot read property 'push' of undefined。但很明显'$ scope.currentOver.balls'数组已定义,那么这里发生了什么?

1 个答案:

答案 0 :(得分:1)

很难从引用的“当前状态”中判断出因为我怀疑重要的缩进已经丢失,但看起来就像currentOver一样,是一个数组,包含具有balls属性的条目(而不是具有自己的balls属性)。所以:

$scope.currentOver[0].balls.push($scope.currentBall);

让我想到的关键点是:

$scope.currentOver: Array[1] <== Here, we're seeing that it's an array with one entry
0: Object                    <== This looks like it's about to show us what that entry is
balls: Array[0]              <== And so I suspect this is in the entry, not the array
bowlerId: 0
...

。例如,我怀疑丢失的缩进可能看起来像这样:

$scope.currentOver: Array[1]
    0: Object
        balls: Array[0]
        bowlerId: 0
...