关于ES6 Symbol迭代器需多次调用next()的问题咨询
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
doneproperty. Instead, every time you callnext(), it returns an object with two properties:value(the current element) anddone(a boolean telling you if the iteration is finished). - In your
do...whileloop, you're checkingiterable.done—this property doesn't exist on the iterator itself, so it evaluates toundefined(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

