Answer the question
In order to leave comments, you need to log in
Why is the console outputting numbers (Symbol.iterator)?
I do
n't understand how this code works. where does the next() function call happen? why does n contain a number?
(in theory, this is an example about creating an iterator using Symbol, which generates Fibonacci numbers)
Answer the question
In order to leave comments, you need to log in
Symbol.iterator
sets the behavior when iterating an object. In the case with for..of
the method next
is called implicitly. But its presence and the appearance of the returned object with fields oblige value
the done
iterator protocol. B value
contains the current value that gets into the variable n
, and done
the iteration end flag is specified.
The same protocol is used, for example, in generators:
function fibonacci(max) {
return {
[Symbol.iterator]: function* iterator() {
let prev = 0
let cur = 1
while (true) {
[prev, cur] = [cur, prev + cur]
if (cur > max) {
return cur
}
yield cur
}
}
}
}
[...fibonacci(1500)] // Массив с числами Фибоначчи с ограничением «1500»
// Но при этом...
const iterable = fibonacci(1500)[Symbol.iterator]()
iterable.next() // {value: 1, done: false}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question