JS /无法读取未定义的属性'push'

时间:2014-12-31 10:31:32

标签: javascript

我在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

它给了我下一个错误:

TypeError: Cannot read property 'push' of undefined

但是,在推送操作之前定义了SpecificArray。

我也尝试:var specificArray = new Array()

1 个答案:

答案 0 :(得分:4)

你应该在条件

上添加一些花括号
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]);
}

没有它,行为就像这样:

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