Moment For Technology

Understand ES6 iterators

Posted on Sept. 23, 2022, 3:41 p.m. by Tom Hooper
Category: The front end Tag: javascript The front end

What is an iterator?

In software development, 'iteration' means the execution of a program several times in sequence, usually with explicit termination conditions.

  • In JS, counting loops are one of the simplest iterations
for(let i=0; i10; i++){
        console.log(i)
}
Copy the code

What implements the iterator interface?

  • string
  • An array of
  • mapping
  • A collection of
  • The arguments object
  • Dom collection type such as NodeList
let str = 'abc'
let arr = ['a'.'b'.'c']
let map = new Map().set('a'.1).set('b'.'2').set('c'.3)
let set = new Set().add('a').add('b').add('c')
let nodeList = document.querySelectorAll('div')
// The iterator returned by the factory function
console.log(str[Symbol.iterator]()) //StringIterator {}
console.log(arr[Symbol.iterator]())//ArrayIterator {}
console.log(map[Symbol.iterator]())//MapIterator {}
/ /...
/ /...
Copy the code

There is no need to explicitly call this factory function to generate iterators during the actual writing of the code. Automatically compatible with receiving iterable objects.

For example, the for... Of, data structures, extension operators, array.from (),Set, Map constructors...

Iterator iterator

demo1

let arr = ['a'.'b'.'c']
/ / the iterator
const iter =  arr[Symbol.iterator]()
// Perform iteration
console.log(iter.next())
console.log(iter.next())
console.log(iter.next())
console.log(iter.next())
Copy the code
  • The results of

We can see that when done is true, the iteration is over

demo2

Iterators are independent and there is no relationship between different iterators

let arr = ['a'.'b']
const iter1 =  arr[Symbol.iterator]()
const iter2 =  arr[Symbol.iterator]()
console.log(iter1.next())
console.log(iter2.next())
console.log(iter1.next())
console.log(iter2.next()) 

Copy the code

demo3

Realize a variety of types of data traversal

// Implement multiple object types traversal
const str = '123',
  arr = [1.2.3],
  map = new Map().set('a'.1).set('b'.2).set('c'.3)
  set = new Set().add(1).add(2).add(3)
  nodeList = document.querySelectorAll('div')
  
const traverse = data=  {
  const iter = data[Symbol.iterator]()
  let flagDone = false
  In addition to while, recursion can also be implemented
  while(! flagDone){const {value, done} = iter.next()
    flagDone = done
    if(! done){console.log(value)
    }
  }
  console.log(The '-')
}

traverse(str)
traverse(arr)
traverse(map)
traverse(set)
traverse(nodeList)
Copy the code
  • The results of

Search
About
mo4tech.com (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.