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

关于ES6 Symbol迭代器需多次调用next()的问题咨询

Why Your Manual Iterator Calls Aren't Working & Better ES6 Alternatives

First off, let's break down what's going wrong in your code, then show you the clean, idiomatic ways to iterate in ES6.

The Root of the Problem

Your code only prints the first character because of a misunderstanding about how iterators work:

  • Iterators themselves don't have a done property. Instead, every time you call next(), it returns an object with two properties: value (the current element) and done (a boolean telling you if the iteration is finished).
  • In your do...while loop, you're checking iterable.done—this property doesn't exist on the iterator itself, so it evaluates to undefined (a falsy value), and the loop stops after the first iteration.

Here's a fixed version of your manual iterator approach that captures the result of each next() call and checks its done property:

const title = "Omkar";
const iterable = title[Symbol.iterator]();
let iterationResult;

do {
    iterationResult = iterable.next();
    // Only log if we haven't reached the end
    if (!iterationResult.done) {
        console.log(iterationResult.value);
    }
} while (!iterationResult.done);

The Better ES6 Way: for...of Loops

Manually calling next() is almost never necessary in ES6—we have the for...of loop specifically designed to handle iterable objects (like strings, arrays, Maps, etc.) automatically. It takes care of calling next() under the hood, checking done, and assigning the current value to a variable:

const title = "Omkar";
for (const char of title) {
    console.log(char);
}

This will print every character in the string without any manual iterator management. For longer strings like "Chewbacca", it works exactly the same way—no need to count how many times to call next().

Other Quick Options

If you just want to process all elements at once, you can also convert the iterable to an array using the spread operator, then use array methods like forEach:

const title = "Omkar";
const characters = [...title];
characters.forEach(char => console.log(char));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:23:58