ES6 Iterator (Iterator) and for. of loop usage method learning (Summary), es6for.

Source: Internet
Author: User

ES6 Iterator (Iterator) and for. of loop usage method learning (Summary), es6for.

1. What is an iterator?

The generator concept is available in Java, Python, and other languages, and ES6 is also added to JavaScript. Iterator allows us to use the next method of the Iterator object instead of initializing the set and the index variables. Instead, it returns the value of the next item of the Set, which is more procedural.

An iterator is an object with special interfaces. Contains a next () method. The call returns an object containing two attributes, value and done. value indicates the value at the current position, and done indicates whether the iteration is complete, if this parameter is set to true, the next call is invalid.

In ES5, The traversal Set is usually a for loop, and the array also has the forEach method. The object is for-in. in ES6, Map and Set are added, the iterator can process all set data in a unified manner. The iterator is an interface. As long as the data structure exposes an iterator interface, the iteration can be completed. ES6 creates a new traversal command for... of loop. The Iterator interface is mainly used for consumption by....

Ii. How to Use the iterator?

1. Default Iterator Interface

As long as the Iterator interface is deployed in the data structure, the data structure is "Iterable ). ES6 stipulates that the default Iterator interface is deployed in the Symbol of the data structure. iterator attribute, or, a Data Structure only needs to have Symbol. iterator data can be considered as "iterable ).

Native data structure for... of consumption

  1. Array
  2. Map
  3. Set
  4. String
  5. TypedArray (a common fixed-length buffer type that allows reading binary data in the buffer)
  6. Arguments object in the function
  7. NodeList object

The above native data structure does not contain objects. Why?

This is because the traversal sequence of object attributes is uncertain and needs to be manually specified by the developer. Essentially, the traversal is a linear processing. For any non-linear data structure, deploying the traversal interface is equivalent to deploying a linear transformation.

To consume objects:

// code1function Obj(value) {  this.value = value;  this.next = null;}Obj.prototype[Symbol.iterator] = function() {  var iterator = {    next: next  };  var current = this;  function next() {    if (current) {      var value = current.value;      current = current.next;      return {        done: false,        value: value      };    } else {      return {        done: true      };    }  }  return iterator;}var one = new Obj(1);var two = new Obj(2);var three = new Obj(3);one.next = two;two.next = three;for (var i of one) {  console.log(i);}// 1// 2// 3

2. Call the Iterator Interface

(1) Deconstruct value assignment

// code2let set = new Set().add('a').add('b').add('c');let [x,y] = set;// x='a'; y='b'let [first, ...rest] = set;// first='a'; rest=['b','c'];

(2) extended Operators

// Code3 // var str = 'hello ';[... str] // ['h', 'E', 'l', 'l', 'O'] // Example 2 let arr = ['B ', 'C']; ['A ',... arr, 'D'] // ['A', 'B', 'C', 'D']

(3) yield * expression in the Generator function (next chapter)

// code4let generator = function* () {yield 1;yield* [2,3,4];yield 5;};var iterator = generator();iterator.next() // { value: 1, done: false }iterator.next() // { value: 2, done: false }iterator.next() // { value: 3, done: false }iterator.next() // { value: 4, done: false }iterator.next() // { value: 5, done: false }iterator.next() // { value: undefined, done: true }

(4) other occasions

  1. For...
  2. Array. from
  3. Map (), Set (), WeakMap (), WeakSet ()
  4. Promise. all ()
  5. Promise. race ()

3. for... of loop advantages

Let's take a look at the disadvantages of the array forEach method:

// code5myArray.forEach(function (value) { console.log(value);});

The problem with this writing is that you cannot jump out of the forEach loop in the middle, and neither the break command nor the return command can take effect.

Let's take a look at the disadvantages of the loop of the object for... in:

for (var index in myArray) { console.log(myArray[index]);};
  1. The key name of the array is a number, but the for... in loop uses a string as the key name, such as "0", "1", and "2.
  2. For... in loop can not only traverse the number key name, but also traverse the manually added recommendation period, and even include the key on the prototype chain.
  3. In some cases, for... in loop meetings Traverse Key names in any order
  4. For... in traversal is mainly designed for Traversing objects and is not applicable to traversing arrays.

So what are the significant advantages of for...?

  1. Has the same concise syntax as for... in, but does not have the disadvantages of for... in
  2. Unlike the forEach method, it can be used with break, continue, and return.
  3. Provides a unified operation interface for traversing all data structures
for (var n of fibonacci) { if (n > 1000) {  break;  console.log(n); }}

4. How to Use the for... of loop for each data type?

(1) array

For... of loop allows retrieving the array to obtain the key value

var arr = ['a', 'b', 'c', 'd'];for (let a in arr) {  console.log(a); // 0 1 2 3}for (let a of arr) {  console.log(a); // a b c d}

For... of loop calls the traversal interface. The array traversal interface only returns the value with a digital index.

let arr = [3, 5, 7];arr.foo = 'hello';for (let i in arr) {  console.log(i); // "0", "1", "2", "foo"}for (let i of arr) {  console.log(i); // "3", "5", "7"}

(2) Map and Set Structures

var engines = new Set(["Gecko", "Trident", "Webkit", "Webkit"]);for (var e of engines) {  console.log(e);}// Gecko// Trident// Webkitvar es6 = new Map();es6.set("edition", 6);es6.set("committee", "TC39");es6.set("standard", "ECMA-262");for (var [name, value] of es6) {  console.log(name + ": " + value);}// edition: 6// committee: TC39// standard: ECMA-262

From the code above, we can see that... the traversal order is based on the order in which each member is added to the data structure. A value is returned for the Set structure, the review of the Map Structure returns an array. The two members of the array are the key names and key values of the current Map Member respectively.

(3) Class array objects

String

// Normal string traversal let str = "yuan"; for (let s of str) {console. log (s); // y u a n} // traverses a string containing 32-bit UTF-16 characters for (let x of 'a \ uD83D \ udc0a') {console. log (x);} // 'A' // '\ uD83D \ udc0a'

DOM NodeList object

let paras = document.querySelectorAll("p");for (let p of paras) { p.classList.add("test");}

Arguments object

function printArgs() { for (let x of arguments) {  console.log(x); }}printArgs("a", "n");// "a"// "n"

No Iterator Interface Class array object traversal Processing

Processing Using the Array. from Method

Let arrayLike = {length: 2, 0: 'A', 1: 'B'}; // error for (let x of arrayLike) {console. log (x);} // correct for (let x of Array. from (arrayLike) {console. log (x );}

(4) object

For common objects, you cannot directly use for... of traversal. Otherwise, an error is reported. You must deploy the Iterator interface to use it. The following two methods are available for deployment:

// Method 1: Use Object. the keys method generates an array for (var key of Object. keys (someObject) {console. log (key + ":" + someObject [key]);} // Method 2: Use the Generator function to repackage the object. function * entries (obj) {for (let key of Object. keys (obj) {yield [key, obj [key] ;}}for (let [key, value] of entries (obj) {console. log (key, "->", value);} // a-> 1 // B-> 2 // c-> 3

Iii. iterator application example

1. Fibonacci Series

Next we will use the iterator to customize our own Fibonacci sequence group. We have two running prerequisites until the Fibonacci sequence is initialized. The first premise is that the first two numbers are 0, 1, the second premise is that each value in the future is the sum of the first two values. In this way, our goal is to output a new value every iteration.

var it = { [Symbol.iterator]() {    return this  },  n1: 0,  n2: 1,  next() {    let temp1 = this.n1,    temp2 = this.n2;    [this.n1, this.n2] = [temp2, temp1 + temp2]    return {      value: temp1,      done: false    }  }}for (var i = 0; i < 20; i++) {  console.log(it.next())}//   "value": 0,  "done": false} {  "value": 1,  "done": false} {  "value": 1,  "done": false} {  "value": 2,  "done": false} {  "value": 3,  "done": false} {  "value": 5,  "done": false}... {  "value": 2584,  "done": false} {  "value": 4181,  "done": false}

2. task queue iterator

We can define a task queue, Which is empty during initialization. After the tasks to be processed are passed in, the data is imported for processing. In this way, the data transmitted for the first time will only be processed by Task 1, and the data transferred for the second time will only be processed by Task 2... The Code is as follows:

Var Task = {actions: [], [Symbol. iterator] () {var steps = this. actions. slice (); return {[Symbol. iterator] () {return this;}, next (... args) {if (steps. length> 0) {let res = steps. shift ()(... args); return {value: res, done: false }} else {return {done: true }}} Task. actions. push (function task1 (... args) {console. log ("Task 1: multiply") return args. reduce (function (x, y) {return x * y})}, function task2 (... args) {console. log ("Task 2: Add") return args. reduce (function (x, y) {return x + y}) * 2}, function task3 (... args) {console. log ("Task 3: subtraction") return args. reduce (function (x, y) {return x-y}); var it = Task [Symbol. iterator] (); console. log (it. next (10,100, 2); console. log (it. next (20, 50,100) console. log (it. next (10, 2, 1) // Task 1: multiply {"value": 2000, "done": false} Task 2: Add {"value": 340, "done": false} Task 3: subtraction {"value": 7, "done": false}

3. delayed execution

Suppose we have a data table. We want to obtain data in order of size, but we don't want to sort it in advance. Maybe we don't want to use it at all, so we can sort the code when we use it for the first time to implement delayed code execution:

var table = {  "d": 1,  "b": 4,  "c": 12,  "a": 12}table[Symbol.iterator] = function() {  var _this = this;  var keys = null;  var index = 0;  return {    next: function() {      if (keys === null) {        keys = Object.keys(_this).sort();      }      return {        value: keys[index],        done: index++>keys.length      };    }  }}for (var a of table) {  console.log(a)} // a b c d

Iv. Conclusion

This chapter focuses on understanding the Iterator interface mechanism and the usage of for... of loops. The next chapter introduces the Generator function.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

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.