Answer the question
In order to leave comments, you need to log in
Question about how a recursive function works?
Write a function that creates a nested UL/LI list (tree) from an object. As I understand it, the createTreeText(obj) function processes nested objects. The logic of work in the if block is not clear. And the return of an empty string will be if the node
is empty
var data = {
"Рыбы": {
"Форель": {},
"Щука": {}
},
"Деревья": {
"Хвойные": {
"Лиственница": {},
"Ель": {}
},
"Цветковые": {
"Берёза": {},
"Тополь": {}
}
}
};
function createTree(container, obj) {
container.innerHTML = createTreeText(obj);
}
function createTreeText(obj) { // отдельная рекурсивная функция
var li = '';
for (var key in obj) {
li += '<li>' + key + createTreeText(obj[key]) + '</li>';
}
if (li) { //(1)
var ul = '<ul>' + li + '</ul>'
}
return ul || '';
}
var container = document.getElementById('container');
createTree(container, data);
Answer the question
In order to leave comments, you need to log in
It is not entirely clear what you are asking about, while it seems that you yourself describe the essence of the function. The principle of the loop for ... in
is such that it simply will not work if the object is empty. Accordingly, if the object is NOT empty and the cycle has passed, then li
data is written to the variable, and since it is not empty, then the condition is met that the elements are nested in the list , otherwise the function will return an empty string. <li>
<ul>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question