开发者问题收集

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

2014-12-31
1183

我在 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个回答

您应该在条件上添加一些花括号

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
Hacketo
2014-12-31