javascript - 有没有更快的方法来显示数组的每个索引
问题描述
我正在创建一个函数,该函数将为数组中的每个项目创建 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
我想知道是否有更快的方法来代替手动切片数组并创建这样的元素,这需要很多时间,特别是如果数组中有很多项目
解决方案
用于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>
推荐阅读
- javascript - 找不到模块'expo/tools/LogReporter'
- artificial-intelligence - VowpalWabbit 预测不正确。如何正确准备学习数据?
- android - BroadcastReceiver.onReceive 多次调用
- mysql - 带有多个子查询优化的 Sql 选择查询
- c# - “GetPhysicalMedicineInfoByOrderNo_Result”上的“BillingPhysicalMedicineId”属性无法设置为“System.Int32”值
- django - django.db.utils.DataError:除以零
- inkscape - 如何在 Inkscape 扩展的 .inx 文件上定义“描边样式”参数?
- azure - 使用 ShardKey 和 MongoAPI 的 CosmosDB 集合的 Azure 搜索索引
- r - 添加一个计数器 lapply(do.call) - R
- localhost - 如何让 Aurelia 在本地 IIS 的本地主机设置下运行