2016-04-08 19 views
1

由於某些原因,我的條件中的else子句重寫了數組中的值,即使它找到了匹配項。任何想法爲什麼發生這種情況?下面的代碼:for循環中的Else子句重寫數組中的值

controller.js

$scope.allAds = DummyAdService.dummyAds; 
    $scope.allStatements = DummyStatementsService.dummyStatements; 

    for(var i=0; i < $scope.allStatements.length; i++) { 
     var statement = $scope.allStatements[i]; 
     for(var j=0; j < $scope.allAds.length; j++) { 
      var ad = $scope.allAds[j]; 
      if(statement.statement.toLowerCase().indexOf(ad.tag) > -1) { 
       statement.ad = ad.url; 
      } else { 
       var randomAd = $scope.allAds[Math.floor(Math.random() * $scope.allAds.length)]; 
       statement.ad = randomAd.url; 
      } 
     } 
    }; 

services.js

function DummyStatement(id, accountId, reportId, timestamp, rating, statement, url) { 
    this.id = id; 
    this.accountId = accountId; 
    this.reportId = reportId; 
    this.timestamp = timestamp; 
    this.rating = rating; 
    this.statement = statement; 
    this.url = url; 
} 

function DummyStatementsService(DummyAccountService) { 
    this.dummyStatements = [ 
     new DummyStatement(1, 1, 1, 1449635098000, 'pos', 
      'Time to visit my second home. Gym haha'), 
     new DummyStatement(2, 1, 1, 1449615098000, 'pos', 
      'Feeling so much better after 10 hours sleep'), 
     new DummyStatement(3, 1, 1, 1440615028000, 'pos', 
      'Excited about going to Thorpe Park tomorrow'), 
    new DummyStatement(16, 2, 1, 1449635098000, 'neg', 
      'What a terrible week it\'s been so far. Weekend can\'t come soon enough'), 
     new DummyStatement(17, 2, 1, 1449615098000, 'neg', 
      'Rain rain rain go away. We all want some sunshine'), 
     new DummyStatement(18, 2, 1, 1440615028000, 'neg', 
    ] 
} 

function DummyAd(id, tag, url) { 
    this.id = id; 
    this.tag = tag; 
    this.url = url; 
} 

function DummyAdService() { 
    this.dummyAds = [ 
     new DummyAd(1, "gym", "ad-gym.jpg"), 
     new DummyAd(2, "sleep", "ad-sleep.jpg"), 
     new DummyAd(3, "thorpe park", "ad-themepark.jpg"), 
    ] 
} 
+1

因爲'statement'是存儲在'$ scope.allStatements [i]'中的元素的引用*。 – poke

+0

好吧,我明白了。 'statement.ad'在for循環中即時創建。在if-else子句的else部分中,我可以做任何事情來檢查它是否存在,然後給它賦值。因爲如果它確實存在,可能是因爲indexOf已經返回true,所以它已經被分配了一個值 – methuselah

回答

0

加入statement = $scope.allStatements[i+1]固定它。

if(statement.statement.toLowerCase().indexOf(ad.tag) > -1) { 
    statement.ad = ad.url; 
    statement = $scope.allStatements[i+1]; 
} else if(statement.statement.toLowerCase().indexOf(ad.tag) === -1) { 
    var randomAd = $scope.allAds[Math.floor(Math.random() * $scope.allAds.length)]; 
    statement.ad = randomAd.url; 
}