This is the 17th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Examples of TypeScript

This article is about iterators.Copy the code

The iterator

JavaScript provides many methods for iterating over collections, from simple for loops to map() and filter().

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. (Official TypeScript documentation)

The symbol. iterator property is itself a function, which is the default iterator generator for the current data structure. Executing this function returns an iterator.

/ / 1
// Define a variable
let name = 'bear'
Return an iterator
let iterator = name[Symbol.iterator]()
/ / print
console.log(iterator.next())      // {value: 'b', done: false}
console.log(iterator.next())      // {value: 'e', done: false}
console.log(iterator.next())      // {value: 'a', done: false}
console.log(iterator.next())      // {value: 'r', done: false}
Copy the code

String is a built-in iterable, and the default iterator for String returns the characters of the current String in turn. The string variable bear in Example 1 finally returns b, e, a, and r.

// Example 1
console.log(iterator.next())      // { value: undefined, done: true }
Copy the code

Calling the next() method after example 1 does not return value.

for offor in

/ / 1
// Demo list
const list = [10.20.30];
// for of statement
for (let i of list) {
    console.log(i);   / / 10, 20, 30
}
// for in statement
for (let i in list) {
    console.log(i);   / / "0", "1", "2",
}
Copy the code

For of and for in can both iterate over lists, but the values used for iteration are different: for of iterates over the values of the object’s keys, while for in iterates over the list of the object’s keys.

/ / 2
const list = [10.20.30];
for (let i of list) {
    console.log(i); 
    console.log(typeof i);  // number, number, number 
}
Copy the code

Why is an array of type number iterated over a value of type string? The print is still number type, should be the official document written wrong.

Functions of iterators 1. Provide a unified and convenient access interface for various data structures. 2. Enable the members of the data structure to be arranged in some order. Create a new traversal command for of loop.

For of iterates over iterable objects (Array, Map, Set, String, TypedArray, Arguments, etc.), calling the symbol. iterator method on the object.

Finish this! If this article helps you at all, please give it a thumbs up.