извлекать элементы из двумерного массива

Вы можете сделать это, используя расширение Select с помощью Func<T, int, TOut>:

var rotatedList = myList.Select(inner => inner.Select((s, i) => new {s, i}))
                        .SelectMany(a => a)
                        .GroupBy(a => a.i, a => a.s)
                        .Select(a => a.ToList()).ToList();

. Это даст вам еще один List<List<string>>.

Breakdown

.Select(inner => inner.Select((s, i) => new {s, i}))

Для каждого внутреннего списка мы проецируем содержимое списка на новый анонимный объект с двумя свойствами: s, строковое значение и i индекс этого значения в исходном списке.

.SelectMany(a => a)

Мы сглаживаем результат до одного списка

.GroupBy(a => a.i, a => a.s)

. Мы группируем по свойству i нашего анонимного объекта (напомним, что это индекс) и выберите s как наши значения (только строка).

.Select(a => a.ToList()).ToList();

Для каждой группы мы изменили перечисление на список и еще один список для всех групп.

0
задан Gonzalo.- 30 March 2019 в 23:25
поделиться

2 ответа

Вам необходимо проверить длину массива ответов для этого вопроса и перебрать каждый ответ:

function generateQuestions() {
    const letters = ['A', 'B', 'C', 'D', 'E', 'F'];
    let gameHTML = "<p class='text-center'>;
    // iterate over each answer:
    answerArray[questionCounter].forEach((answer, index) => {
       const letter = letters[index] + '.';
       gameHTML += "<p class='answer'>" + letter + answer + "</p>"
    })
    $("#mainArea").html(gameHTML);
};
0
ответ дан jsdeveloper 30 March 2019 в 23:25
поделиться

Вероятно, вам следует использовать цикл для этого, даже когда вы знаете число, просто чтобы сделать код более понятным (например, чтобы вам не приходилось переписывать логику в случае изменения числа).

[ 1110] Например, вы можете динамически составить список таких вопросов:

    const questionsArray = [
        ["What's my favorite color?"], 
        ["Describe my favorite toy."]
     ];

    const mainContainer = document.querySelector("#mainContainer");
    for(let i = 0; i < questionsArray.length; i++){

      // Makes a node to hold the question text
      let qTextNode = document.createTextNode(questionsArray[i]);

      // Makes a paragraph element to display the question text in
      let qParagraph = document.createElement("p");

      // Makes a div element to hold this question and all its possible answers
      let qContainer = document.createElement("div");

      // Gives the container some distinguishing attributes
      qContainer.classList.add("question");
      qContainer.id = (i + 1);

      // Puts the text in the paragraph
      qParagraph.appendChild(qTextNode);

      // Puts the paragraph in the container
      qContainer.appendChild(qParagraph);

      // Adds the container (and everything inside it) to the page
      mainContainer.appendChild(qContainer);

    }
    // Prints out the HTML we just created
    console.log(mainContainer.outerHTML.split("><").join(">\n<"));
<div id="mainContainer"></div>

. Как и во многих случаях, когда вы запускаете сниппет, но, как вы можете видеть в консоли, теперь у вас есть организованная структура для всех ваших вариантов ответов, чтобы жить. Позже может появиться код javascript и найти конкретные элементы на вашей странице, как и стили CSS . [+1112]

Вот вычурная версия, которая добавляет текст ответа на каждый вопрос. Для этого нам нужен цикл внутри цикла (поскольку у каждого вопроса есть несколько вариантов ответов, которые мы хотим динамически добавить):

const questionsArray = [
        ["What's my favorite color?"], 
        ["Describe my favorite toy."]
      ];
const answersArray = [
        ["black", "green", "yellow", "orange"], 
        ["big","small","long"], 
      ];

    // Stuff you saw in the previous snippet
    const mainContainer = document.querySelector("#mainContainer");
    for(let i = 0; i < questionsArray.length; i++){
      let qTextNode = document.createTextNode(questionsArray[i]);
      let qParagraph = document.createElement("p");
      let qContainer = document.createElement("div");
      qContainer.classList.add("question");
      qContainer.id = (i + 1);
      qParagraph.appendChild(qTextNode);
      qContainer.appendChild(qParagraph);
    
      // Makes an "ordered list" element to hold the choices
      let aList = document.createElement("ol");
      
      // Letters array will be used for item IDs
      let letters = "A,B,C,D,E,F,G,H,I,J".split(",");          

      // A nested loop to add the choices
      for(let j = 0; j < answersArray[i].length; j++){

        // Makes a textNode to hold the current choice
        let aTextNode = document.createTextNode(answersArray[i][j]);

        // Makes a list-item element to display the choice text in
        let aItem = document.createElement("li");

        // Gives the item an id using question number & answer letter
        aItem.id = (i + 1) + letters[j];

        // Puts the choice text in the item
        aItem.appendChild(aTextNode);

        // Puts the item in the list
        aList.appendChild(aItem);
      }

    // Done looping through choices, this adds the list to the question container
    qContainer.appendChild(aList);

  // And... we're back to stuff from the previous snippet
    mainContainer.appendChild(qContainer);
  }
  console.log(mainContainer.outerHTML.split("><").join(">\n<"));
/* The visible letters for the list items come from here, not from the script */
ol{ list-style-type: upper-alpha; }
.question{ margin-top: 25px; }
<div id="mainContainer"></div>

0
ответ дан Cat 30 March 2019 в 23:25
поделиться
Другие вопросы по тегам:

Похожие вопросы: