for循环中的Else子句重写数组中的值

时间:2016-04-08 11:11:45

标签: angularjs

由于某种原因,我的条件中的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 个答案:

答案 0 :(得分: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; } 修复此问题。

{{1}}