繁体   English   中英

如何合并 2 个相同长度的 arrays 以获得彼此相邻的值?

[英]How do I merge 2 arrays of same length to get values next to each other?

例如:

如果我有 2 arrays 这样的:

let array1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
let array2 = [1, 2, 3, 4, 5, 6, 7];

如何使用这样的li标签制作ul

<li> a 1 </li>
<li> b 2 </li>
<li> c 3 </li>
<li> d 4 </li>
<li> e 5 </li>
<li> f 6 </li>
<li> g 7 </li>

先感谢您!

您可以使用 for 循环来实现这一点,此代码在每个循环中创建一个 li 元素,并将 arrays 中的索引值分配为 textContent(这适用于两个长度相等的 arrays)

 let list = document.getElementById('list'); let array1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g']; let array2 = [1, 2, 3, 4, 5, 6, 7]; for(let i = 0; i < array1.length; i++){ let li = document.createElement('li'); list.appendChild(li); li.textContent = array1[i] + ', ' + array2[i]; }
 <ul id="list"> </ul>

所以基本上我们想先动态创建 HTML 个元素并将其分配给主体。 然后我们要遍历数组并相应地分配内容(注意,这仅在两个 arrays 具有相同长度时才有效)。 您可以在此处了解更多信息 Web API https://www.w3schools.com/jsref/met_node_appendchild.asp

    const array1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
    const array2 = [1, 2, 3, 4, 5, 6, 7];

    const unorderedList = document.createElement('ul')
    const body = document.querySelector('body')

    body.appendChild(unorderedList)

    for(let i=0; i < array1.length; i++) {
      const listItem = document.createElement('li')
      listItem.innerText=`${array1[i]} ${array2[i]}`
      unorderedList.appendChild(listItem)
   }

您还可以使用 Array.map 并将两个 arrays 合并为一个 object。

 let array1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g']; let array2 = [1, 2, 3, 4, 5, 6, 7]; let objArr = array1.map((item, idx) => ({ key1: item, key2: array2[idx] })); objArr.forEach(item => { const exampleList = document.getElementById('example'); const listItem = document.createElement('li'); const data = document.createTextNode(`${item.key1} ${item.key2}`); listItem.appendChild(data); exampleList.appendChild(listItem); } )
 <ul id="example"> </ul>

您可以使用 forEach 创建和存储列表元素,然后使用 innerHtml 将创建的列表项插入到 ul 标签中。

 const array1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g']; const array2 = [1, 2, 3, 4, 5, 6, 7]; const list = document.getElementById("list"); // Selects the list element let listItem = ""; // Creates innerHTML for ul element array1.forEach((element, index) => listItem += `<li> ${element} &nbsp; ${array2[index]} </li>`) // Insert listItems to ul element list.innerHTML = listItem;
 #list { list-style-type: none; }
 <ul id="list"></ul>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM