首页 > 解决方案 > 如何修复 foreach forEach 不是函数

问题描述

我对编程很陌生,当我执行 forEach 函数时,我的应用程序返回错误。我的 controller.js 中有以下代码

$scope.ajaxRequest = A.Game.get({action: 'game',id: user.id});
          $scope.ajaxRequest.$promise.then(function(){                                      
                $scope.ajaxRequest.game.forEach(function(entry) {
                    if(cards.indexOf(entry) !== -1) {
                        console.log('alredy in game');
                    } else {
                        if(entry.id != user.id){
                            cards.push(entry);                                
                            $scope.imageLocations.push(entry.photo);
                        }
                    }
                });




我的控制台给了我这个错误

ionic.bundle.js:26799 TypeError: $scope.ajaxRequest.game.forEach is not a function
    at controllers.js:2383
    at processQueue (ionic.bundle.js:29132)
    at ionic.bundle.js:29148
    at Scope.$eval (ionic.bundle.js:30400)
    at Scope.$digest (ionic.bundle.js:30216)
    at Scope.$apply (ionic.bundle.js:30508)
    at done (ionic.bundle.js:24829)
    at completeRequest (ionic.bundle.js:25027)
    at XMLHttpRequest.requestLoaded (ionic.bundle.js:24968)

标签: javascriptionic-framework

解决方案


这个

          $scope.ajaxRequest.$promise.then(function(){                                      
                $scope.ajaxRequest.game.forEach(function(entry) {

看起来很腥。将其更改为

          $scope.ajaxRequest.$promise.then(function(result) {                                      
                result.forEach(function(entry) {

现在,我不会在没有看到结果的情况下保证它会起作用,但这是使用异步调用和承诺的模式:在.then块中,放置一个使用承诺链中前一个输出的函数作为争论。所以至少这个改变

          $scope.ajaxRequest.$promise.then(function(result) {                                      

(而不是$scope.ajaxRequest.$promise.then(function() {)是必要的。


推荐阅读