You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自定义Symbol.iterator遍历多层嵌套数组仅返回部分元素问题求解

错误原因

你的写法存在两个核心问题:

  1. 没有保存内层数组的遍历状态:每次next()方法被调用时,你都会直接从外层迭代器arr取新的子数组,只要内层循环返回第一个值就直接结束本次next调用,当前子数组剩余的内层元素永远不会被遍历到。
  2. 外层迭代器定义位置错误:你把外层迭代器arr定义在Symbol.iterator方法外部,该对象只能被正确迭代一次,第二次迭代时arr已经遍历完成,会直接返回空数组。
修复方案

在迭代器内部维护两个状态:外层数组的迭代器、当前正在遍历的内层子数组的迭代器,每次next调用时优先从内层迭代器取值,内层迭代器遍历完成后再切换到下一个外层子数组。
修复后的代码如下:

const array = [
  [["first_name" , "First"], ["image" , "image"]],
  [["email" , "email"]],
  [["last_name","last_name"]],
  [["password" , "password"], ["password", "password"]]
]

let obj = {
  [Symbol.iterator]: function () {
    // 每次迭代都重新生成外层迭代器,支持多次迭代
    const outerIterator = array.values();
    let currentInnerIterator = null;
    return {
      next() {
        // 循环直到拿到有效值或者遍历完成
        while(true) {
          // 如果当前有内层迭代器,先尝试从内层取值
          if (currentInnerIterator) {
            const innerRes = currentInnerIterator.next();
            if (!innerRes.done) {
              return {
                done: false,
                value: innerRes.value[1]
              }
            }
            // 内层遍历完成,清空状态
            currentInnerIterator = null;
          }
          // 内层没有值了,去外层取下一个子数组
          const outerRes = outerIterator.next();
          if (outerRes.done) {
            // 外层也遍历完成,结束
            return { done: true }
          }
          // 更新内层迭代器为新的子数组的迭代器
          currentInnerIterator = outerRes.value.values();
        }
      },
    };
  },
}

console.log([...obj]) // 输出 ["First", "image", "email", "last_name", "password", "password"]

内容的提问来源于stack exchange,提问作者Double H

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 11:18:02