如何使用for循环迭代angularjs中的json对象?

时间:2016-07-20 18:05:22

标签: javascript angularjs json

我有一个数组我想迭代它在迭代过程中我们检查一个条件如果条件为真我们返回一个值否则我们返回其他部分我写了一些代码但它不起作用。                  如果条件为真,循环将不会终止我怎么能做任何人帮助我的那个?

 $scope.bgImages = []; //it having some objects
 $scope.job = []; //it also having some objeccts
 //if both elements are matching we return one value
 $scope.getJobDepartmentImg = function() {
     var jobDepartment = $scope.job.department;
     for (var i in $scope.bgImages) {
         var department = $scope.bgImages[i].departmentName;
         var job_header = $scope.bgImages[i].s3ImageUrl;
         if (jobDepartment === department) {
             return job_header;
         } else {
             return default_job_header;
         }
     }
 };

如果条件满足,那么循环不会终止,任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

在其他声明之外再做一次回报

$scope.getJobDepartmentImg = function() {
        var jobDepartment = $scope.job.department;
        for (var i in $scope.bgImages) {
            var department = $scope.bgImages[i].departmentName;
            var job_header = $scope.bgImages[i].s3ImageUrl;
            if(jobDepartment === department){
                return job_header;
            }
        }
        return default_job_header;
}

它将迭代数组并返回job_header如果找到一个,或者如果循环结束则返回默认值