C
C
Christina2018-10-07 01:08:22
JavaScript
Christina, 2018-10-07 01:08:22

How to output recursively?

I saw a lot of examples, everything is difficult to describe, I can not understand what's what. Explain in a simple way, please, how the code works in this case?
I don't understand how it works exactly, so I can't do what I need. Code with the right example.

function createData(l) {
  let item = '';
  for(let key in l) {
    let data = l[key];
    item += typeof data === 'string' ? `<li>${data}` : `<li><ul class="list">${createData(data)}</ul>`;
  }
  return item;
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Roman, 2018-10-07
@KrisIris

Christina , I am laying out for your court my attempt to explain the essence of recursion. The code has comments.

code with explanation
// итак, пусть будет задан некий абстрактный массив 
// с произвольной глубиной вложенности
// при этом элементами массива могут быть
// строки и вложенные массивы
const arr = [
  "string 1",
  "string 2",
  [
    "string 3.1",
    "string 3.2",
    [
      "string 3.3.1",
      [
        "string 3.3.2.1",
        "string 3.3.2.2"
      ],
      "string 3.3.3",
    ]
  ],
  "string 4",
  [
    "string 5.1",
    [
      "string 5.2.1",
      [
        "string 5.2.2.1",
        "string 5.2.2.2"
      ],
      "string 5.2.3"
    ]
  ]
];

// так как глубина вложенности произвольная
// для обхода всех элементов оптимальным
// будет использовать рекурсивную функцию
function parseArray(data) {
  let retstr = '';
  if(typeof data === "string"){
    // если строка, то выводим ее 
    // содержимое как элемент текущего списка
    retstr += '<li>'+data+'</li>';
  }else if(Array.isArray(data) ){
    // если массив, то создаем влеженный список
    retstr += '<ul>';
    // и каждый элемент массива отдаем на обработку
    // нашей функции, вызывая ее из нееже (это и есть рекурсия)
    // таким образом мы обеспечиваем обход
    // всех элементов нашей древовидной структуры
    // независимо от ее глубины вложенности и порядка
    // следования элементов
    data.forEach(value=>{
      retstr += parseArray(value);
    });
    // после прохода всех элементов внутри текущего
    // массива закрываем текущий список
    retstr += `</ul>`;
  }
  return retstr;
}


let wrap = document.querySelector('.wrap');
wrap.innerHTML = parseArray(arr);

V
Vladimir Proskurin, 2018-10-07
@Vlad_IT

I didn't quite understand what you didn't understand.
Here is the createData function, it draws a list of elements from the array, which is passed to it in the l parameter. All.
In the function, we go through each value from l. There is a condition: if l is a string, then we display it in li, if it is an array, then it is probably a list of child elements that need to be output in a separate ul block. For this purpose, recursively (recursively, it means calling the function itself), we call the createData function and pass it not an array of all elements, but only an array of child elements of the current element from the loop. And everything is the same there again, we look at the elements, if the element has child elements, we again call createData.

S
sunblossom, 2018-10-07
@sunblossom

It's not recursion. Simply put, recursion is when a function calls itself or two functions mutually call each other.
Here, an array is passed to the loop, which, through the in operator, is read element by element into key, and then output. And also the initialization of the data variable is clearly redundant here.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question