Consider this python code
it = iter([1, 2, 3, 4, 5])
for x in it:
print x
if x == 3:
break
print '---'
for x in it:
print x
it prints 1 2 3 --- 4 5
, because the iterator it
remembers its state across the loops. When I do seemingly the same thing in JS, all I get is 1 2 3 ---
.
function* iter(a) {
yield* a;
}
it = iter([1, 2, 3, 4, 5])
for (let x of it) {
console.log(x)
if (x === 3)
break
}
console.log('---')
for (let x of it) {
console.log(x)
}
What am I missing?
for...of Vs for...inThe for...in loop is used to iterate through the keys of an object. The for...of loop cannot be used to iterate over an object. You can use for...in to iterate over an iterable such arrays and strings but you should avoid using for...in for iterables. The for...of loop was introduced in ES6.
The only difference between them is the entities they iterate over: for..in iterates over all enumerable property keys of an object. for..of iterates over the values of an iterable object.
Yes. But hunting it down is a littlebit complicated, as for of doesn't only iterate arrays (like for in does enumerate objects). Instead, it generically iterates all iterable objects - in the order that their respective iterator supplies.
The main difference between them is in what they iterate over. The for...in statement iterates over the enumerable string properties of an object, while the for...of statement iterates over values that the iterable object defines to be iterated over.
Generator objects in JS are not reusable unfortunately. Clearly stated on MDN
Generators should not be re-used, even if the for...of loop is terminated early, for example via the break keyword. Upon exiting a loop, the generator is closed and trying to iterate over it again does not yield any further results.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With