使用 underscore.js 的嵌套 .each 循环

Nested .each loop using underscore.js

如何在 underscore.js 中编写此代码?

for(var i=0; i<scope.courseContent.sections.length; i++){
        if(scope.courseContent.sections[i].pages.length){
            ctrl.pages.push({'content': scope.courseContent.sections[i].content});
            for(var j=0; j<scope.courseContent.sections[i].pages.length; j++){
                ctrl.pages.push({'content':scope.courseContent.sections[i].pages[j].content});
            }
        }
        else{
            if(scope.courseContent.sections[i].title == 'Course Title' || scope.courseContent.sections[i].title == 'Introduction'){
                ctrl.pages.push({'content':scope.courseContent.sections[i].content});
            }
        }
}

我使用嵌套的 .each 循环尝试了这个,但这并没有起作用。这是我的方法:

_.each(scope.courseContent.sections, function(sections){
        if(sections.pages.length){
            ctrl.pages.push({'content': scope.courseContent.sections.content});
            _.each(sections.pages, function(page){
                ctrl.pages.push({'content':scope.courseContent.sections.pages.content});    
            });
        }
        else{
            if(scope.courseContent.sections.title == 'Course Title' || scope.courseContent.sections.title == 'Introduction'){
                ctrl.pages.push({'content':scope.courseContent.sections.content});
            }
        }
});

问题是 sectionspages 等是数组,在原始代码中,因为我们使用 for 循环,所以使用 [=14 之类的迭代索引访问项目=],但是通过你的下划线尝试,你试图使用 . 直接从数组访问每个项目的属性,这不会按预期工作。

当你使用下划线时,你将每个项目作为回调的第一个参数,所以我认为你的代码应该是:

_.each(scope.courseContent.sections, function(section) {
  if (section.pages.length) {
    ctrl.pages.push({
      'content': section.content
    });
    _.each(section.pages, function(page) {
      ctrl.pages.push({
        'content': page.content
      });
    });
  } else if (section.title == 'Course Title' || section.title == 'Introduction') {
      ctrl.pages.push({
        'content': section.content
      });
    }
});

或者您可以在回调签名中添加第二个参数,这将是当前项目的索引,例如:

_.each(scope.courseContent.sections, function(section,i) {

并像原始代码一样访问具有索引的项目:scope.courseContent.sections[i].content,但这是不必要的。