javascript - 如何修复 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)
解决方案
这个
$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() {
)是必要的。
推荐阅读
- c++ - 如何将向量分配给参考变量?
- mysql - 准备语句中的语法错误
- visual-studio - visual studio 2017 无法包含某些文件,但 d3d 应用程序可以调试
- linux - 未在 Linux EC2 实例启动上运行的命令
- php - How to convert particular text of a webpage into hindi using css or script
- magento2 - Magento 2.2.4 + Database migration Undefined offset: 1 vendor/magento/data-migration-tool/src/Migration/Step/Eav/Data.php on line 291
- node.js - NodeJS ES6:类模块导出
- javascript - ES6: React destructure immutable state with and without spread
- react-native - 如何使用带有图像源的道具来创建反应原生的可用组件?
- jquery - How to set value using jQuery in PHP foreach loop()?