在javascript中嵌套对象到LI

问题描述 投票:-2回答:2

如何从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>
javascript html-lists
2个回答
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>

0
投票

您可以使用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>
© www.soinside.com 2019 - 2024. All rights reserved.