An iterator is a special object that conforms to the iterator protocol specification. In TypeScript, we can define an interface that has a function type next, and the return value of the next() method is {value: any, done: Boolean}. Value is of type any, indicating the next value to be returned. Done is a Boolean that returns true if there is no more data to return. The iterator also holds an internal pointer to the position of the value in the current collection.

Once an iterator is created, the iterator object can be iterated explicitly by repeatedly calling next().

Simulate a shorthand iterator

// Declare an Iterator interface with a function type such as next
interface IteratorInterface {
  next: () = > {
    value: any
    done: boolean
  }
}

// Declares a function that returns an Iterator object whose return value type must conform to the Iterator interface
function createIterator(array: any[]) :IteratorInterface {
  let index = 0
  let len = array.length

  return {
    next: function () {
      return index < len ? { value: array[index++], done: false}, {value: undefined.done: true}}}}var iterator = createIterator([1.2.3])

console.log(iterator.next()) // { value: 1, done: false }
// Get the next item in the dataset by calling the next() method on the iterator

console.log(iterator.next()) // { value: 2, done: false }
console.log(iterator.next()) // { value: 3, done: false }
console.log(iterator.next()) // { value: undefined, done: true }
// When all data is in the data set, the done attribute changes to true
Copy the code

Can be iterative

An object is considered iterable when it implements the symbol. iterator property. Some of the built-in types such as Array, Map, Set, String, Int32Array, Uint32Array etc have implemented their respective symbol. iterators. The symbol. iterator function on the object is responsible for returning values for iteration.

String is a built-in iterable:

let str: string = 'Hi'
console.log(typeof str[Symbol.iterator]) // function
Copy the code

The default iterator for String returns the characters of the String in turn:

// A string variable with the default iterator generator symbol. iterator built in
let str: string = 'Hi'
// This function returns an iterator
let iterator: IterableIterator<string> = str[Symbol.iterator]() 
 
console.log(iterator.next())      // { value: 'H', done: false }
console.log(iterator.next())      // { value: 'i', done: false }
console.log(iterator.next())      // { value: undefined, done: true }
Copy the code

Iterators are used for:

  • Provides a unified, easy access interface for various data structures (Array, Map, Set, String, etc.).
  • Allows the members of a data structure to be arranged in some order.
  • A new traversal command was createdfor.. ofCycle.

The for… of

for… Of iterates over iterable objects (including Array, Map, Set, String, TypedArray, Arguments, and so on), calling the symbol. iterator method on the object.

Iterative array

Example:

let iterable = [10.20.30]
/ / by the for... The of loop iterates through each element of the group iterable
for (const value of iterable) {
  console.log(value)
}
// Output 10, 20, 30
Copy the code

Example:

const heroes = [
  {
    name: 'athey'.gender: 2
  },
  {
    name: 'Tydamir'.gender: 1}]for (let { name } of heroes) {
  console.log(name)
}
Copy the code

The let {name} of heroes loop iterates through the heroes array, deconstructing each object to get the name property value for each object

Iterating string

Strings are iterable through for… To iterate through each character quickly:

let iterable = 'abc'

for (const s of iterable) {
  console.log(s)
}
// Output a, B, and c
Copy the code

Iterative Map

let iterable = new Map()

iterable.set('a'.1)
iterable.set('b'.2)
iterable.set('c'.3)

for (let entry of iterable) {
  console.log(entry)
}
// ['a', 1]
// ['b', 2]
// ['c', 3]

for (let [key, value] of iterable) {
  console.log(value)
}
/ / 1
/ / 2
/ / 3
Copy the code

Explanation: A Map object iterates based on the insertion order of the elements in the object. for… The of loop returns an array of the form [key, value] after each iteration. Using the let [key, value] deconstruction form, you can quickly obtain the value of each attribute.

The for… Of with the for… The difference in

for.. Of and the for… In can iterate over a list; But the values used for iteration are different, for.. In iterates over the list of the object’s keys, while for.. Of iterates over the value of the key of the object.

let list = [4.5.6];

for (let i in list) {
    console.log(i); / / "0", "1", "2",
}

for (let i of list) {
    console.log(i); / / "4", "5", "6"
}
Copy the code

for… In can operate on any object, and it provides a way to view object properties. But for… Of focuses on the value of the iterable. The built-in Map and Set objects already implement symbol. iterator methods that give us access to the values they hold.

let pets = new Set(["Cat"."Dog"."Hamster"]);
pets["species"] = "mammals";
//pets-- Set(3) { 'Cat', 'Dog', 'Hamster', species: 'mammals' }
for (let pet in pets) {
    console.log(pet); // "species"
}

for (let pet of pets) {
    console.log(pet); // "Cat", "Dog", "Hamster"
}
Copy the code

Deconstruct assignment and extension operators

Destructuring arrays and Set structures calls the symbol. iterator method by default:

let [head, ...tail] = [1.2.3.4]
// tail = [2, 3, 4]
Copy the code

The extension operator also calls the default Iterator interface to get an array structure:

let arr = [...'hello']
console.log(arr) // ['h','e','l','l','o']
Copy the code

Learning links

  • www.tslang.cn/docs/handbo…
  • www.imooc.com/wiki/typesc…