javascript中的LI嵌套对象

时间:2019-03-09 13:50:49

标签: javascript html-lists

如何从JavaScript中的嵌套数组返回单个li? 我希望a,b,c为

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

代替

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

这是我在做什么(also on 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 个答案:

答案 0 :(得分:1)

提供了要显示数组中所有元素的信息,您必须使用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>

答案 1 :(得分:0)

您可以使用forEach并在递归函数中使用Array.isArrayArray.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>