May 07, 2021 TypeScript
When an object implements the
Symbol.iterator
we consider it it iterative. S
ome built-in
Array
Map
Set
String
Int32Array
Uint32Array
have
Symbol.iterator
The
Symbol.iterator
for returning the value for iteration.
for..of
statement
for..of
traverses iterative objects and calls the
Symbol.iterator
object. H
ere's how to use
for..of
simple example of of of:
let someArray = [1, "string", false];
for (let entry of someArray) {
console.log(entry); // 1, "string", false
}
for..of
vs.
for..in
statement
for..of
and
for..in
can iterate on a list, but the value used for iteration is different,
for..in
iterates is a
list of
the keys of the
for..of
the value corresponding to the key of the iterative object.
The following example shows the difference between the two:
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"
}
Another difference is
for..in
can manipulate any object; B
ut
for..of
on the value of the iterative object.
The
Map
Set
and
Symbol.iterator
method so that we can access the values they save.
let pets = new Set(["Cat", "Dog", "Hamster"]);
pets["species"] = "mammals";
for (let pet in pets) {
console.log(pet); // "species"
}
for (let pet of pets) {
console.log(pet); // "Cat", "Dog", "Hamster"
}
When the build target is ES5 or ES3, the iterator is only allowed on the
Array
type. U
se for: on non-array
for..of
statement gets an error, even if these non-array values have implemented the
Symbol.iterator
The compiler generates a
for
loop as
for..of
such as:
let numbers = [1, 2, 3];
for (let num of numbers) {
console.log(num);
}
The generated code is:
var numbers = [1, 2, 3];
for (var _i = 0; _i < numbers.length; _i++) {
var num = numbers[_i];
console.log(num);
}
When the target is an ECMAScipt 2015-compatible engine, the compiler generates the
for..of
built-in iterator implementation.