Вложенный объект в LI в JavaScript - PullRequest
0 голосов
/ 09 марта 2019

Как вы возвращаете отдельный li из вложенного массива в javascript?Я бы хотел, чтобы a, b, c были

<li>a</li>
<li>b</li>

вместо

<li>a,b,c,</li>

Вот что я делаю ( также на jsFiddle ):

var spellingList = ["Word1", ["a", "b", "c"], "Word2", "Word3"];
// for loop should run through spelling list array and create list items in "listSpelling"

for (var i = 0; i < spellingList.length; i++) {
  // create a new li
  var newLI = document.createElement("li");
  var indSpellingWord = spellingList[1];

  // grab the spelling list item 
  var newContent = document.createTextNode(indSpellingWord);


  // add the spelling list item to the li
  newLI.appendChild(newContent);

  // get the unordered list and add the new li
  var displaySpellList = document.getElementById("listSpelling");
  displaySpellList.appendChild(newLI);
}
<div id="theSpellingList">
  <h3>The Spelling List</h3>
  <ul id="listSpelling">
  </ul>
</div>

Ответы [ 2 ]

1 голос
/ 09 марта 2019

При условии, что вы хотите показать все элементы в массиве, вы должны сгладить массив, используя flat :

var spellingList = [ "Word1", ["a", "b", "c"], "Word2", "Word3" ];
var flattenSpellingList = spellingList.flat();

for (var i = 0; i < flattenSpellingList.length; i++) {
  // create a new li
  var newLI = document.createElement("li");
  var indSpellingWord = flattenSpellingList[i];

  // grab the spelling list item 
  var newContent = document.createTextNode(indSpellingWord);

  // add the spelling list item to the li
  newLI.appendChild(newContent);

  // get the unordered list and add the new li
  var displaySpellList = document.getElementById("listSpelling");
  displaySpellList.appendChild(newLI);
}
<div id="theSpellingList">
  <h3>The Spelling List</h3>
  <ul id="listSpelling"></ul>
</div>
0 голосов
/ 09 марта 2019

Вы можете использовать forEach и Array.isArray внутри рекурсивной функции. Array.isArray, чтобы проверить, является ли текущий элемент при итерации массивом. Если это так, то вызовите ту же функцию.

Также используйте литералы шаблона для чистого кода

var spellingList = ["Word1", ["a", "b", "c"], "Word2", "Word3"];
let text = '';


function createList(elem) {
  elem.forEach(function(item) {
    if (Array.isArray(item)) {
      createList(item)
    } else {
      text += `<li>${item}</li>`;
    }
  })
  listSpelling.innerHTML = text;
}
createList(spellingList)
<div id="theSpellingList">
  <h3>The Spelling List</h3>
  <ul id="listSpelling">
  </ul>
</div>
...