Iterators and for-of Loops

Source: Internet
Author: User

How do we iterate through the elements in the array? 20 years ago when JavaScript was first born, you could implement array traversal like this:

 for (var index = 0; index < myarray.length; index++) {console.log (Myarray[index]);}

Since ES5 is officially released, you can use the built-in ForEach method to iterate through the array:

Myarray.foreach (function  (value) {Console.log (value);});

This code looks more concise, but there is a small flaw in this approach: you cannot break the loop with the breaks statement, nor can you use the return statement to return to the outer function. Of course, it would be nice to iterate through the array elements with only the syntax for the For loop. Well, you'll want to try the for-in loop:

 for (varin// don't do this Console.log (Myarray[index]);}

This is definitely a bad choice, why?

1, in this code, the value assigned to index is not the actual number, but the string "0", "1", "2", it is possible to inadvertently do string arithmetic calculation, for example: "2" + 1 = "21", which brings great inconvenience to the coding process.

2. The for-in loop body, which acts on an array, iterates through the array elements, as well as the custom attributes. For example, if you have an enumerable attribute Myarray.name in your array, the loop will be executed extra once, traversing to the index named "name". Even the properties on the array prototype chain can be accessed.

3. Most shocking of all, in some cases, this code may traverse array elements in random order.

4. In short, for-in is designed for ordinary objects, and you can iterate through the keys of the string type, so it is not suitable for array traversal.

a powerful for-of cycle

ES6 will not destroy the JS code you have written. For now, thousands of web sites rely on for-in loops, some of which even use them for array traversal. If you want to increase the array traversal support by modifying the for-in loop, it will make all this more confusing, so the standard committee has added a new loop syntax to the ES6 to solve the current problem. Just like this:

 for (var  value of MyArray) {Console.log (value);}

Yes, does this cycle look familiar compared to the previous built-in approach? Well, we're going to explore what powerful features are hidden beneath the exterior of the for-of loop. Now, just remember:

1. This is the simplest and most straightforward syntax for iterating over array elements

2. This method avoids all defects in the for-in cycle

3. Unlike ForEach (), it responds correctly to break, continue, and return statements

var arr = [1, 3, 5, 7, 9];          function getneed () {             varnull;               for (var  value of arr) {                 if (value = = 5)                     {return Huhu = value;                 }                 Console.log (value);             }         }         Console.log (Getneed ());

The for-in loop is used to iterate through the object properties. For-of loops are used to traverse data-for example, values in an array. But not only that!

for-of loops can also traverse other collections.

The for-of loop supports not only arrays, but also most class array objects, such as DOM NodeList objects. The for-of loop also supports string traversal, which treats a string as a series of Unicode characters to traverse:

 for (var chr of "") {alert (CHR);}

It also supports MAP and Set object traversal. I'm sorry, you've never heard of the Map and Set objects. They are the new type in ES6. We will explain these two new types in a follow-up article. If you've used maps and sets in other languages, you'll find that there's not much of a difference in ES6.

For example, a Set object can automatically exclude duplicates:

// Create a set object based on a word array var New Set (words);

Once the Set object is generated, you can easily traverse what it contains:

 for (var  Word of Uniquewords) {console.log (word);}

The Map object is slightly different: the included data consists of a key-value pair, so you need to use deconstruction (destructuring) to disassemble the key-value pair into two separate variables:

 for (var+ "s phone number is:" + value);}

Deconstruction is also a new feature of ES6, which we will explain in a separate article. It seems that I should record these excellent topics, and there are too many new content in the future that require one by one anatomy. Now, you just have to remember: the future of JS can use some new collection classes, and even more types will be born, and for-of is to traverse all these collections specifically designed loop statements. 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+ ":" + Someobject[key]);}
Deep understanding

ES6 always adhere to the purpose of the new addition to the characteristics of the other language is bound to be a strong practical proof. For example, the newly added for-of loop looks like a looping statement in C + +, Java, C #, and Python. Like them, the for-of loop here supports several different data structures that are available in the language and standard libraries. It is also an extension point in this language: for extension points, reference 1 is recommended. Analysis of Extension point 2. What is extensions and extension points?).

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];

OK, I know what you're thinking, that [symbol.iterator] syntax looks strange, what does this code do? 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.

As you probably guessed, Symbols is a new type in ES6, and we'll explain it in a follow-up article. 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

Now you won't have to implement an object iterator yourself from scratch, and we'll explain it in more detail in the next article. To help you understand this article, let's take a quick look at the iterator (if you skip this chapter, you'll miss out on the wonderful technical details).

The for-of loop will call this method repeatedly, once per loop. For example, this piece of code is the simplest iterator I can think of:

var zeroesforeveriterator =functionreturn this   functionreturnfalse, 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.

The design of this iterator, along with its. done and. Value properties, is not the same on the surface as iterators in other languages. In Java, iterators have separate. Hasnext () and. Next () methods. In Python, they have only one. Next () method, which throws a stopiteration exception when there are no more values. But all of these three designs fundamentally return the same information.

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. The first is the for-of loop:

 for (VAR of iterable) {some statements}

Then there is an example that is quite similar to the previous one, using the following method and a little temporary variable:

var $iterator = Iterable[symbol.iterator] (); var $result = $iterator. Next ();  while (!  == $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.

When can I start using this new feature?

At present, for the new features of the for-of cycle, all the latest versions of Firefox (in part) support (starting from the FF 13 to support the relevant features, FF 36-FF 40 basic support for most features), in Chrome can be accessed by chrome://flags and enable "experimental JavaScript" to support. Microsoft's Spartan browser is supported, but IE is not supported. If you want to use this new syntax in a Web environment and need to support IE and Safari, you can use Babel or Google's Traceur compilers to translate your ES6 code into a web-friendly ES5 code.

On the server side, you do not need a similar compiler, io.js in the default support ES6 new Syntax (section), in Node need to add--harmony option to enable related features.

true}

Yo OK, here's what we're going to do today, but the use of the for-of loop is far from over. There's a new object in ES6 that fits perfectly with the for-of loop, and I don't mention it because it's the subject of our next week's article, and I think this new feature is ES6 's most fantastic place, and if you haven't encountered it in a language like Python and C #, You'll probably find it unbelievable at first, but it's the simplest way to write an iterator, and it's very useful in refactoring, and it's likely to change the way we write asynchronous code, whether in a browser or server environment, so be sure to take a closer look at the ES6 in the next week's easy-to-read ES6 Generator: Generators.

Iterators and for-of Loops

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.