The core concept

The iterator pattern provides a way to access the elements of an aggregate object sequentially without exposing the internal representation of the object.

Iterators are divided into internal iterators and external iterators.

The inner iterator defines the rules of iteration internally. The outside world does not care about the implementation inside the iterator, and the interaction with the iterator is only an initial call.

Js has many implementations of internal iterators, such as each method, map method, etc. Here is an example:

['a'.'b'.'c'.'d'].forEach((char, index) = > {
  console.log(`the ${index + 1} letter is ${char}`)})// the 1 letter is a
// the 2 letter is b
// the 3 letter is c
// the 4 letter is d
Copy the code

External iterators are iterations where the user decides when to proceed to the next element. For example:

var Iterator = function (obj) {
  var current = 0
  var next = function () {
    current += 1
  }
  var isDone = function () {
    return current >= obj.length
  }
  var getCurrItem = function () {
    return obj[current]
  }
  return {
    next: next,
    isDone: isDone,
    getCurrItem: getCurrItem,
  }
}
var compare = function (iterator1, iterator2) {
  while(! iterator1.isDone() && ! iterator2.isDone()) {if(iterator1.getCurrItem() ! == iterator2.getCurrItem()) {throw new Error(Iterator1 and iterator2 are not equal)
    }
    iterator1.next()
    iterator2.next()
  }
  alert(Iterator1 is equal to iterator2)}var iterator1 = Iterator([1.2.3])
var iterator2 = Iterator([1.2.3])
compare(iterator1, iterator2) Iterator1 is equal to iterator2
Copy the code

In addition to iterating over synchronous queues, external iterators can also be used to iterate over asynchronous queues so that asynchronous queues can proceed sequentially. Just like vue-Router execution of the navigational guard, which uses external iterators, Vue-Router stuffs various navigational guards and functions that load asynchronous components into a queue, and by building external iterators, the asynchronous tasks are executed sequentially.