首页 > 解决方案 > 有没有更快的方法来显示数组的每个索引

问题描述

我正在创建一个函数,该函数将为数组中的每个项目创建 ap 元素

  const liArray = ["hello", "hi", "hello", "test", "hey"];

  const parentElement= document.getElementById("myDiv");
  const index1 = liArray.slice(-1);
  const p = document.createElement("p");
  p.innerHTML = "1. " + index1;
  parentElement.appendChild(p);
  
  const index2 = liArray.slice(-2, -1);
  const p2 = document.createElement("p");
  p2.innerHTML =  "2. " + index2;
  parentElement.appendChild(p2);
  
  const index3 = liArray.slice(-3, -2);
  const p3 = document.createElement("p");
  p3.innerHTML =  "3. " + index3;
  parentElement.appendChild(p3);
   
  const index4 = liArray.slice(-4, -3);
  const p4 = document.createElement("p");
  p4.innerHTML =  "4. " + index4;
  parentElement.appendChild(p4);
 
  const index5 = liArray.slice(-5, -4);
  const p5 = document.createElement("p");
  p5.innerHTML =  "5. " + index5;
  parentElement.appendChild(p5);

所以结果将是

1. hello
2. hi
3. hello
4. test
5. hey

我想知道是否有更快的方法来代替手动切片数组并创建这样的元素,这需要很多时间,特别是如果数组中有很多项目

标签: javascripthtmljquery

解决方案


用于Array.prototype.forEach()循环遍历数组的每个元素。

尝试这个

const liArray = ["hello", "hi", "hello", "test", "hey"];

const parentElement = document.getElementById("myDiv");

liArray.forEach((currentValue, index) => {
  var elm = document.createElement('p');
  elm.innerHTML = `${index + 1}. ${currentValue}`;
  parentElement.appendChild(elm);
});
<div id="myDiv"></div>


推荐阅读