S
S
someserj2017-10-21 22:20:42
JavaScript
someserj, 2017-10-21 22:20:42

Why is the console outputting numbers (Symbol.iterator)?

SGZr1N4TTDeSWbH5qT6wxA.png
I do
9zm_r-CeRbmJfgFE3ZYEcA.png
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

1 answer(s)
D
Danakt Frost, 2017-10-21
@Danakt

Symbol.iteratorsets the behavior when iterating an object. In the case with for..ofthe method nextis called implicitly. But its presence and the appearance of the returned object with fields oblige valuethe doneiterator protocol. B valuecontains the current value that gets into the variable n, and donethe 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 question

Ask a Question

731 491 924 answers to any question