Iterators and for-of

Source: Internet
Author: User
Tags iterable

In ES5 and before the JS standard, we are accustomed to use for (var i = 0; i < array.length;i++) {//todo} or for (var index in Array) {Console.log (Array[index]) ;} or foreach

The former is good, and then two more problems, foreach can not be enough return or break interrupt loop, the index in Array returns the index is not a number, but the string "0", "1", "2" and so on, thus deriving a powerful for-of


for-of

for (var value of Array) {

Console.log (value);

}

avoided all for-in flaws. The for-in loop is used to iterate through the object properties, and the for-of loop is used to iterate through the data-the values in the array.

The for-of loop supports all class array objects, such as Dom NodeList objects.

For-of also supports string traversal, which considers a string as a series of Unicode characters to traverse:

for (Var chr of "") {

Console.log (CHR);

}

The object traversal of map and set is also supported (these two types are ES6 new, if you have used in other languages, with little difference in ES6).

For-of loops do not support ordinary objects, but if you want to iterate over an object's properties, you can use the for-in loop (which is also its job) or the built-in Object.keys () method:

To output an enumerable property of an object to the console
for (var key of Object.keys (Someobject)) {
Console.log (key + ":" + Someobject[key]);
As with For/foreach statements in other languages, the FOR-OF Loop statement iterates through the various collections by means of a method. arrays, maps objects, sets objects, and other objects in our discussion have one thing in common, and they all have an iterator method.

You can add an iterator method to any type of object.

When you add the Myobject.tostring () method to an object, you can convert the object to a string, and similarly, when you add the Myobject[symbol.iterator] () method to any object, you can traverse the object.

For example, suppose you are using jquery, although you are very fond of the. each () method, but you still want the jquery object to support the for-of loop, you can do this:


Because jquery objects are similar to arrays
You can add an iterator method that is consistent with the array
Jquery.prototype[symbol.iterator] = Array.prototype[symbol.iterator];


Here, the name of the method is processed by the symbol. The standard committee can name this method the. Iterator () method, but if your code objects may also have some. Iterator () method, this will certainly make you feel very confused. Instead of using a string, symbol is used as the method name in the ES6 standard.

Now, you need to keep in mind that, based on the new criteria, you can define a brand new symbol, just like symbol.iterator, so that there is no conflict with any existing code. The cost of doing this is that the syntax of this code looks slightly stiff, but it can bring so much new features and functionality to you, and everything you do can be completely backwards compatible.

All objects that have [Symbol.iterator] () are referred to as iterations. In the following article, you will find that the concept of an iterative object is almost in the whole language, not only the for-of loop, but also the map and set constructors, the deconstruction assignment, and the new expansion operator.

Iterator Object


var zeroesforeveriterator = {
[Symbol.iterator]: function () {
return this;
},
Next:function () {
return {done:false, value:0};
}
};

Each time you call the. Next () method, it returns the same result, and there are two possible results returned to the for-of loop: (a) We have not completed the iteration; (b) The next value is 0. This means (value of Zeroesforeveriterator) {} will be an infinite loop. Of course, iterators are generally not so simple.
An iterator object can also implement the optional. return () and. throw (exc) methods. If the for-of loop exits prematurely, the. return () method is called, and an exception, break statement, or return statement can trigger a premature exit. If an iterator needs to perform some cleanup or freeing of resources, it can be implemented in the. return () method. Most iterator methods do not need to implement this method: the use of the throw (exc) method is even more special-the for-of loop never calls it. But we will explain the role in more detail in the next article.

Now that we know all the details, we can write a simple for-of loop and then rewrite the iterated object by calling the following method.


For (VAR of iterable) {
Some statements
}

var $iterator = Iterable[symbol.iterator] ();
var $result = $iterator. Next ();
while (! $result. Done) {
VAR = $result. Value;
Some statements
$result = $iterator. Next ();
}
This code does not show how the return () method is handled, and we can add this part of the code, but I think it's too complicated for what we're explaining. The for-of cycle is easy to use, but it has a very complex mechanism behind it.

Iterators and for-of

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.