Copyright
Article reprinted from: HTTPS://GITHUB.COM/ZHONGSP
It is recommended that you jump directly to the URL above to see the latest version.
The scalability of the iteration
When an object implements a Symbol.iterator
property, we consider it to be iterative. Some of the built-in types such as,,,, Array
Map
Set
String
Int32Array
, Uint32Array
etc. have been implemented individually Symbol.iterator
. The function on the object Symbol.iterator
is responsible for returning the value for the iteration.
for..of
Statement
for..of
Iterates over an object that is iterated, calling properties on the object Symbol.iterator
. The following is a simple example used on an array for..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 over a list, but the values used for the iteration are different, the for..in
iteration is the list of keys for the object, and the for..of
value corresponding to the numeric key of the Iteration 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"
One difference is that for..in
you can manipulate any object; it provides a way to view the properties of an object. But for..in
focus on the value of the Iteration object. Built-in Objects Map
and Set
properties have been implemented Symbol.iterator
so that we can access the values they hold.
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"}
Code generation targets are ES5 and ES3
When the build target is ES5 or ES3, iterators are only allowed on Array
types. Using a statement on a non-array value for..of
will get an error, even if these non-array values have already implemented the Symbol.iterator
property.
The compiler generates a simple for
loop as a for..of
loop, for example:
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);}
Target is ECMAScript 2015 or higher
When the target is an engine that is compatible with Ecmascipt 2015, the compiler generates a for..of
built-in iterator implementation for the corresponding engine.
Reprint: "TypeScript Chinese Introductory Course" 15, can be iterated