Simple ES6 (ii): Iterators and for-of loops __ES6

Source: Internet
Author: User
Tags chr data structures iterable new set

How we traverse the elements in the array. When JavaScript first started 20 years ago, you might have done array traversal:

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

After the ES5 is officially released, you can use the built-in foreach method to traverse 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 an interrupt statement, and you cannot return to the outer function using the returns statement.

Of course, it would be nice to just traverse the array element with the syntax for the For loop.

So, you want to try the for-in cycle:

For (var index in myarray) {//Never do this
  Console.log (Myarray[index]);
}

This is definitely a bad choice, for what? In this piece of code, the value assigned to index is not the actual number, but the string "0", "1", "2", it is very likely that the string arithmetic calculation, such as: "2" + 1 = "21", which brings great inconvenience to the coding process. The for-in loop body acting on an array also traverses the custom attribute in addition to traversing the array elements. For example, if you have an enumerable property myarray.name in your array, the loop executes one extra time, traversing to the index named "name". Even the attributes on an array prototype chain can be accessed. Most shocking of all, in some cases, this code may traverse an array element in random order. In short, for-in is designed for ordinary objects, and you can iterate through the keys of the string type, so it does not apply to array traversal. a powerful for-of cycle

Remember in the "Simple ES6 (a): ES6 is what" I promised you. ES6 won't break the JS code you've already written. For now, thousands of web sites rely on for-in loops, some of which are even used for array traversal. If you want to increase array traversal support by modifying the for-in loop, this makes all the more confusing, so the standard committee adds a new loop syntax to the ES6 to solve the current problem.

Just like this:

for (var value of myarray) {
  console.log (value);
}

Yes, this cycle looks a bit familiar compared to the previous built-in methods. Well, we're going to explore what powerful features are hidden beneath the for-of cycle. Now, just remember: This is the simplest and most straightforward syntax for traversing the elements of an array. This method avoids all the flaws in the for-in Loop and foreach (), it responds correctly to the break, continue, and return statements

For-in loops are used to traverse object properties.

For-of loops are used to traverse data-for example, the values in an array.

But not only that. The for-of loop 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 for traversal:

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

It also supports the traversal of map and set objects.

I'm sorry, you've never heard of a map and set object. They are the new type in ES6. We will explain these two new types in subsequent articles. If you have used map and set in other languages, you will find that there is not much discrepancy in ES6.

For example, a set object can automatically exclude duplicates:

Create a set object based on the word array
var uniquewords = new set (words);

After you build the Set object, you can easily traverse what it contains:

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

The map objects are slightly different: the contained data is composed of key-value pairs, so you need to use deconstruction (destructuring) to split the key value pairs into two separate variables:

for (var [key, value] of Phonebookmap) {
   Console.log (key + "' s phone number is:" + value);
}

Deconstruction is also a new feature of ES6, which we will explain in another article. It seems that I should keep track of these excellent topics and that there will be too many new content in the future to be one by one dissected.

Now, you just have to remember: Future JS can use some new type of collection class, even more types will be born, and for-of is to traverse all these sets specially designed loop statement.

For-of loops do not support normal 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:

Outputs an enumerable property for the console for
(var key of Object.keys (Someobject)) {
  Console.log (key + ": + Someobject[key]);
}
Deep Understanding

"Can work in imitation, the skillful thief." "--Pablo Bicasso

ES6 always adhere to the purpose of this: all new features, it is bound to be in other languages have strong practical proof.

For example, the new for-of loop is like a looping statement in C + +, Java, C #, and Python. Like them, the for-of loop supports several different data structures that are available in languages 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 are extensions and extension points?).

As with For/foreach statements in other languages,for-of loop statements are used to traverse various collections by means of a method. arrays, maps objects, sets objects, and other objects that we're talking about have one thing in common, they all have an iterator method.

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

When you add a myobject.tostring () method to an object, you can convert the object to a string, and as 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 much in love with the. each () method, but you still want the jquery object to support the for-of loop, you can do this:

Because the JQuery object is similar to an array
//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? The name of the method is processed here through symbol. The standard committee can name this method as the. Iterator () method, but if the object in your code may have some. Iterator () method, this will certainly make you very confused. Symbol is used as a method name in the ES6 standard instead of a string.

As you probably guessed, symbols is a new type in ES6, which we'll explain in a later 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, which guarantees that there will be no conflict with any existing code. The price of this is that the syntax of the code looks slightly stiff, but it can bring you so many new features and new features, and everything you do can be perfectly backwards compatible.

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

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

The for-of Loop first invokes the [Symbol.iterator] () method of the collection, followed by a new iterator object. An iterator object can be any object with a. Next () method, and the for-of loop will call this method repeatedly, one at a time. For instance, this code is the simplest iterator I can think of:

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

Each time you call the. Next () method, which returns the same result, there are two possible results to return to the for-of loop: (a) We have not yet completed the iteration; (b) The next value is 0. This means that (value of Zeroesforeveriterator) {} will be an infinite loop. Of course, the iterator is not so simple in general.

The design of this iterator, as well as its. Done and. Value properties, is superficially different from the iterator in other languages. In Java, iterators have separate. Hasnext () and. Next () methods. In Python, they have only one. Next () method that throws a Stopiteration exception when there are no more values. But all three designs fundamentally return the same information.

An iterator object can also implement an optional. return () and. throw (exc) method. If the for-of loop exits prematurely, the. return () method is invoked, and an exception, a break statement, or a return statement can trigger a premature exit. If the iterator needs to perform some cleaning 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 its role in more detail in the next article.

Now that we have all the details, we can write a simple for-of loop and then call the overridden object in the following way.

The first is the for-of cycle:

For (VAR of iterable) {
  some statements
}

This is followed by an approximate equivalent of the previous example, using the following methods and a few temporary variables:

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, we can add this part of the code, but I think it is too complicated for the content we are explaining. The for-of cycle is simple 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 are (partially) supported (from FF 13 to support the relevant features, FF 36-FF 40 basic support for most features), in Chrome, you can access the Chrome://flags and enable the " Experimental JavaScript "to support. Microsoft's Spartan browser support, but IE does not support. 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 web-friendly ES5 code.

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

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.