2016-04-08 5 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 statement = $scope.allStatements[i+1]を追加することによって、それを修正

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

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; 
} 
関連する問題