如何循环遍历带断点的多维数组?

How to loop through a multidimensional array with breakpoints?

我意识到 'breakpoint' 可能不是正确的术语。

我有

var sections = [0, 1, 2, 3, 4, 5, 6, 7],
    questions = [];

每个部分有 X 个问题,每个部分的问题数量可能不同。我需要能够在任何给定时间只显示一个部分的问题。因此,section[0] 可能有三个问题。我希望能够只查看这三个问题,写下答案,然后进入下一部分。为此,我有 HTML。我只是缺少 jQuery 中基本上是 "ok, no more questions for this section, move to next section." 的部分 我该怎么做?我可能没有使用正确的术语。我现在拥有的是

$.each(sections, function(i, section) {
    $.each(questions, function(j, question) {
        // stuff to show questions
    });
});

假设 sections 数组中的每个 section 都是 question 项的数组,您可以简单地定位 [=16= 的 value 属性 ] 你别名为 section:

var sections = [
        [{ questionId: 1 }, { questionId: 2 }, { questionId: 3 }], //questions for section 1
        [{ questionId: 1 }, { questionId: 2 }, { questionId: 3 }, { questionId: 4 }, { questionId: 5 }], //questions for section 2
        [{ questionId: 1 }, { questionId: 2 }] //questions for section 3
    ];

$.each(sections, function(i, section) {
    console.log("section " + i + ":");

    $.each(section, function(j, question) {
        console.log("\t" + question.questionId);
    });
});

jsfiddle 演示一些示例功能

您希望在每个部分中包含一系列问题 object/items 来构建这些部分。如果您需要一个完全不同的结构,其中包含用于部分的单独数组和用于问题的单独数组,则此功能需要更改,因为您需要通过标识符将给定问题与给定部分相关联。

这是使用 filter():

实现该目标的一种方法的示例
var sections = [
    { sectionId: 1 },
    { sectionId: 2 },
    { sectionId: 3 },
    { sectionId: 4 },
    { sectionId: 5 },
];

var questions = [
    { questionId: 1, sectionId: 1 },
    { questionId: 2, sectionId: 1 },
    { questionId: 3, sectionId: 2 },
    { questionId: 4, sectionId: 3 },
    { questionId: 5, sectionId: 1 },
    { questionId: 6, sectionId: 4 },
    { questionId: 7, sectionId: 1 },
    { questionId: 8, sectionId: 5 }
];

console.log("**********Example 2**********")
$.each(sections, function(index, section) {
    console.log("Section " + section.sectionId + ":");

    var relatedQuestions = questions.filter(function(question) {
        return question.sectionId === section.sectionId;
    });

    $.each(relatedQuestions, function(index, question) {
        console.log("\tQuestion " + question.questionId);
    });
});