如何在JavaScript中按索引同时遍历两个Map
解决方案:同步遍历两个Map的对应索引项
要实现按索引同步遍历两个Map,你可以先将两个Map的键值对转换为数组,然后通过索引关联两个数组的对应项,在单个循环中完成处理。
具体步骤与代码
- 将两个Map的键值对转换为数组(利用Map的
entries()方法,结合Array.from()转为可通过索引访问的数组) - 遍历其中一个数组的同时,通过索引获取另一个数组的对应项
- 在循环内同时处理两个Map的键值对,完成你的HTML生成逻辑
// 将两个Map转为键值对数组 const map1Entries = Array.from(myMap1.entries()); const map2Entries = Array.from(myMap.entries()); let counter = 1; let htmlSkelton = ''; // 遍历第一个数组,同步获取第二个数组的对应项 map1Entries.forEach(([key1, value1], index) => { // 获取第二个Map对应索引的键值对,处理长度不一致的情况 const [key2, value2] = map2Entries[index] || []; // 输出你需要的遍历格式 console.log(`Iteration-${index + 1} : ${key1}, ${value1}, ${key2}, ${value2}`); // 处理第一个Map的项,保留原有的HTML逻辑 const array1 = key1.split(":::"); htmlSkelton += "<tr>"+ "<th scope='row'>"+(counter++) +"</th>"+ "<td>"+(array1[1] ?? array1[0])+"</td>"+ // 兼容无:::分隔的键 "<td>"+array1[0]+"</td>"+ "<td>"+value1+"</td>"+ "</tr>"; // 处理第二个Map的项,确保存在对应项再执行 if (key2 && value2) { const array2 = key2.split(":::"); htmlSkelton += "<tr>"+ "<th scope='row'>"+(counter++) +"</th>"+ "<td>"+(array2[1] ?? array2[0])+"</td>"+ "<td>"+array2[0]+"</td>"+ "<td>"+value2+"</td>"+ "</tr>"; } });
关键说明
- Map的遍历顺序是插入顺序,转换为数组后,索引对应的就是插入时的顺序,完全匹配你的需求
- 加入了
map2Entries[index] || []和if (key2 && value2)的判断,避免两个Map长度不一致时出现报错 - 保留了你原有的
split(":::")和HTML生成逻辑,同时扩展为处理两个Map的内容
内容的提问来源于stack exchange,提问作者ArrchanaMohan
相关产品推荐
相关产品推荐

