My idea is that, if obj
is an iterable, then each time the obj[Symbol.iterator]
function is invoked, it spits out a brand new iterator. Now, aMap.entries()
gives back an iterable, so:
map = new Map([["a", 3], ["b", 'hi'], ["c", true]]);
for (const e of map.entries()) {
console.log(e);
}
for (const e of map.entries()) {
console.log(e);
}
const someEntries = map.entries();
console.log(someEntries.next());
console.log(someEntries[Symbol.iterator]);
console.log(someEntries[Symbol.iterator]().next());
console.log(someEntries[Symbol.iterator]().next());
console.log(someEntries[Symbol.iterator]().next());
console.log(someEntries[Symbol.iterator]().next());
So that's why the for-of
loop above can print out all key-value pairs twice.
However, the last 6 lines of the code, when I invoke that function and use next()
, it gave a "continuation" of the next()
function... so it is not a brand new iterator but the old one. So this conflicts with the idea that "each time the obj[Symbol.iterator]
function is invoked, it spits out a brand new iterator".
So what does that mean? Each time the obj[Symbol.iterator]
function is invoked, it spits out a iterator, but it can be an old iterator, or it can be a new iterator? There is no guarantee?
For example, the following code shows that it spits out a new iterator each time:
const arr = [1, 3, 5];
console.log(arr[Symbol.iterator]().next());
console.log(arr[Symbol.iterator]().next());
console.log(arr[Symbol.iterator]().next());