如何在同一for循环中使用多个.entries()遍历两个txt文件数据
同循环遍历两个文本文件内容的实现方案
JS 原生不支持你写的在单个 for...of 语句里用 && 拼接两个迭代器的语法,根据你实际需要的配对逻辑,可以选下面几种实现方式:
按相同行号一一对应遍历(最常用)
如果你是要把两个文件的第N行配对处理,直接在遍历第一个文件的循环里,用当前索引取第二个文件对应位置的内容即可,性能最高。如果两个文件行数不一致,默认遍历到更短的那个文件末尾就停止,避免取值越界:
如果需要处理长文件多出来的尾部内容,在循环结束后单独遍历剩余条目即可。const loopCount = Math.min(txtfile1.length, txtfile2.length); for (const [index, value] of txtfile1.entries()) { if (index >= loopCount) break; const index2 = index; const value2 = txtfile2[index]; console.log(`${index}: ${value} and ${index2}: ${value2}`); }全量两两配对遍历
如果你需要第一个文件的每一行,都和第二个文件的所有行分别匹配处理(即求两个文件行内容的笛卡尔积),用两层嵌套循环即可,注意两个循环的索引变量不要重名:for (const [index, value] of txtfile1.entries()) { for (const [index2, value2] of txtfile2.entries()) { console.log(`${index}: ${value} and ${index2}: ${value2}`); } }同步迭代两个非数组类迭代器
如果你手里的txtfile1、txtfile2不是提前读好内容的数组,是逐行读取的迭代器对象,可以手动获取两个迭代器的遍历实例,每次同步取两个迭代器的下一个值,直到任意一个迭代器遍历结束:const iterator1 = txtfile1.entries(); const iterator2 = txtfile2.entries(); let item1, item2; while ( !(item1 = iterator1.next()).done && !(item2 = iterator2.next()).done ) { const [index, value] = item1.value; const [index2, value2] = item2.value; console.log(`${index}: ${value} and ${index2}: ${value2}`); }
内容的提问来源于stack exchange,提问作者dev
相关产品推荐
相关产品推荐

