Welcome to wechat public account: Front Reading Room
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.
for.. Of the statement
for.. Of iterates over the iterable, calling the symbol. iterator method on the object. Here is using for.. on an array A simple example of of:
let someArray = [1."string".false];
for (let entry of someArray) {
console.log(entry); // 1, "string", false
}
Copy the code
for.. of vs. for.. In statement
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
Another difference is for.. In can operate on any object; It provides a way to view the properties of an object. But for.. Of focuses on the value of the iterated object. 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";
for (let pet in pets) {
console.log(pet); // "species"
}
for (let pet of pets) {
console.log(pet); // "Cat", "Dog", "Hamster"
}
Copy the code
Code generation
The targets are ES5 and ES3
When the generation target is ES5 or ES3, iterators are only allowed on Array types. Use for.. on non-array values. The of statement gets an error even if the non-array values already implement the symbol. iterator attribute.
The compiler generates a simple for loop for… Of loops, for example:
let numbers = [1.2.3];
for (let num of numbers) {
console.log(num);
}
Copy the code
The generated code is:
var numbers = [1.2.3];
for (var _i = 0; _i < numbers.length; _i++) {
var num = numbers[_i];
console.log(num);
}
Copy the code
Target ECMAScript 2015 or higher
When the target engine is ECMAScipt 2015 compliant, the compiler generates the engine’s for.. The of built-in iterator implementation.
Welcome to wechat public account: Front Reading Room