Or Smith
Or Smith

Reputation: 3616

JS / Cannot read property 'push' of undefined

I have the following code in JS:

if (all[j][i][11] != Boolean(1) && $scope.w[j][i] != undefined && $scope.ip[j][i] != undefined && $scope.type[j][i] != undefined)
            var specificArray = []
            specificArray.push($scope.w[j][i]);
            // continue with the code

it gives me the next error:

TypeError: Cannot read property 'push' of undefined

But specificArray is defined just before the push operation.

I also try: var specificArray = new Array()

Upvotes: 0

Views: 1183

Answers (1)

Hacketo
Hacketo

Reputation: 4997

You should add some curly braces on the condition

if (all[j][i][11] != Boolean(1) && $scope.w[j][i] != undefined && $scope.ip[j][i] != undefined && $scope.type[j][i] != undefined){
    var specificArray = []
    specificArray.push($scope.w[j][i]);
}

Without it the behavior is like this:

if (all[j][i][11] != Boolean(1) && $scope.w[j][i] != undefined && $scope.ip[j][i] != undefined && $scope.type[j][i] != undefined){
    var specificArray = [];
}
specificArray.push($scope.w[j][i]); // Cannot read property 'push' of undefined

Upvotes: 4

Related Questions