在angular.forEach上获取TypeError

时间:2016-07-28 18:47:02

标签: javascript angularjs

我对AngularJS相对较新,我收到的错误我并不完全理解。在这段代码中,我得到了一个类型错误(如下所列)。错误将我指向sprint.users这一行是一组用户。

$scope.countThisUserSprintsCompleted = function (user) {
    var thisUserTotalSprintsCompleted = 0;
    angular.forEach($scope.sprints, function(sprint) {
        angular.forEach(sprint.users, function (sprintUser, index) {

            if(sprintUser.username == user.username && sprint.status == 'complete') {
                thisUserTotalSprintsCompleted++;
            }
        });
    });
    return thisUserTotalSprintsCompleted;
};



angular.js:13642 TypeError: Cannot read property 'users' of undefined
at userController.js:2123
at Object.q [as forEach] (angular.js:336)
at m.$scope.countThisUserSprintsCompleted (userController.js:2122)
at fn (eval at compile (angular.js:14539), <anonymous>:4:357)
at m.$digest (angular.js:17211)
at angular.js:17417
at e (angular.js:5912)
at angular.js:6191

1 个答案:

答案 0 :(得分:0)

这意味着,使用提供的代码,sprint未定义。

由于您应该在sprint回调中获得angular.forEach,因此undefined内的值可能为$scope.sprints

举个例子:

&#13;
&#13;
[1, undefined, 2].forEach(function(value){
    console.log(value); 
});
&#13;
&#13;
&#13;

要解决此问题(更多补丁),您可以在使用sprint之前添加一项检查:

&#13;
&#13;
[{ test: "value" }, undefined, { test: "other value" }].forEach(function(value){
  if (value) console.log(value.test); 
});
&#13;
&#13;
&#13;

如果您当时没有期望undefined值,则应在进入$scope.sprints之前调查forEach并尝试解决问题。