如何在JavaScript的for...of循环中实现类似Python zip的双迭代功能
在JavaScript中实现Python的zip遍历功能
方法一:基于索引直接遍历
通过数组索引访问对应位置的元素,先取两个数组的最短长度避免越界:
const b = [2, 3, 5]; const d = [['e1', 'e2', 'e3'], ['i1', 'i2'], ['o1', 'o2', 'o3', 'o4']]; const minLength = Math.min(b.length, d.length); for (let i = 0; i < minLength; i++) { const a = b[i]; const c = d[i]; instruction(a, c); }
方法二:自定义zip生成器(更贴近Python写法)
实现一个生成器函数zip,返回可迭代的元素对,配合for...of和解构赋值,逻辑和Python的zip完全对齐:
// 自定义zip生成器,支持任意数量的数组输入 function* zip(...arrays) { const minLength = Math.min(...arrays.map(arr => arr.length)); for (let i = 0; i < minLength; i++) { yield arrays.map(arr => arr[i]); } } // 使用示例 const b = [2, 3, 5]; const d = [['e1', 'e2', 'e3'], ['i1', 'i2'], ['o1', 'o2', 'o3', 'o4']]; // 通过解构赋值获取对应位置的元素 for (const [a, c] of zip(b, d)) { instruction(a, c); }
关于你尝试的写法说明
你写的for (const a of b, const c of d)不符合JavaScript语法,for...of只能遍历单个可迭代对象。通过自定义zip生成器,我们让它每次返回包含两个数组对应位置元素的数组,再通过解构赋值[a, c]拿到变量,这就和Python的for a,b in zip(c,d)实现了相同的效果。
内容的提问来源于stack exchange,提问作者mthgn
相关产品推荐
相关产品推荐

