[JS Master Road] ES6 series Tutorials-iterators, generators, For...of,entries,values,keys, etc.

Source: Internet
Author: User

Then the above [JS Master Road] ES6 series tutorial-iterator and builder details continue.

A new loop structure was introduced in ES6 for ... of, mainly used to iterate over an iterative object, so what is an iterative object?

An iterative object typically has a Symbol.iterator property, and you can print an array with Console.dir in the console, Map,set, which can be found on their prototype object (prototype). This property is closely related to iterators, which can be used to return an iterator, and I'll cite an example below. In general, all collection objects (arrays, set,map, and strings) are objects that can be iterated. There are default iterators in these objects.

For: The traversal principle of the of cycle:

Each time the loop executes, the next () method of the Iterator object is called, and the Value property of the result object returned by the iterator is stored in a variable, and the loop continues the process until done returns true

1 ]; 2  for (let Val of values) {3    Console.log (val); 4 }

This for...of loop code obtains an iterator by invoking the Symbol.iterator method of the values array, which is done automatically by the JS engine, and then the next () method of the iterator is called multiple times, returning the value of the object and storing it in the variable Val. In order: Ten, the 30,done is true when the exit, and finally will not assign the undefined to Val.

Access the default iterator with Symbol.iterator

 1  let userlist = [' Ghostwu ', ' Goku ', ' Eight commandments ' ];
    2  let iterator = Userlist[symbol.iterator] (); 3  Console.log (Iterator.next ()); // {value: ' Ghostwu ', done:false}  4  Console.log (Iterator.next ()); // {value: ' Goku ', done:false}  5  Console.log (Iterator.next ()); // {value: ' Eight commandments ', done:false}  6  Console.log (Iterator.next ()); // {value:undefined, done:false}  

Because objects with the Symbol.iterator property have a default iterator, this feature can be used to detect whether an object is an iterative object.

1 functionisiterable (obj) {2     return typeofObj[symbol.iterator] = = = ' function ';3 }4Console.log (Isiterable ([10, 20, 30]));//true5Console.log (isiterable ("GHOSTWU"));//true6Console.log (Isiterable (NewMap ()));//true7Console.log (Isiterable (NewSet ()));//true8Console.log (Isiterable (NewObject ()));//false9Console.log (Isiterable ({}));//false

So, for.. of cannot traverse object (JSON)

var obj = {    ' ghostwu    ',    ' n ', ' Man '};  for var val of obj) {    Console.log (val);}

The above traversal method, will be error.

However, we can add an iterator method to the object

1Let obj = {2 items: [],3*[Symbol.iterator] () {4          for(Let item of This. Items) {5 yield item;6         }7     }8 }9Obj.items.push (10 );TenObj.items.push (20 ); OneObj.items.push (30 ); A variterator =Obj[symbol.iterator] (); -Console.log (Iterator.next ());//{value:10, done:false} -Console.log (Iterator.next ());//{value:20, done:false} theConsole.log (Iterator.next ());//{value:30, done:false} -Console.log (Iterator.next ());//{value:undefined, done:true}

Add a generator to the Symbol.iterator property, then the object has the function of an iterator, then you can use the For...of method

1Let obj = {2 items: [],3*[Symbol.iterator] () {4          for(Let item of This. Items) {5 yield item;6         }7     }8 }9Obj.items.push (10 );TenObj.items.push (20 ); OneObj.items.push (30 ); A  -  for(let Val of obj) { - Console.log (val); the}

Built-in iterators:

An iterative object that has the following 3 types of iterators built in

Entries (): Returns an iterator with the value of a key value pair

VALUES (): Returns an iterator that values the value of the collection

Keys (): Returns an iterator with the value of all the keys in the collection

1Let userlist = [' Ghostwu ', ' Goku ', ' eight commandments ' ];2 3  for(Let name of Userlist.entries ()) {4 Console.log (name);5 }6 7Let set =NewSet ([10, 20, 30 ] );8  for(Let num of set.entries ()) {9 console.log (num);Ten } One  ALet map =NewMap ([[' Name ', ' GHOSTWU '], [' Age ', 22 ] ] ); -  for(Let detail of map.entries ()) { - console.log (detail); the}

Entries returns a key-value pair, note the set collection, and returns the same key and value.

 1  let set = new  set ([Ten, 30 ] ); 2   ( Let num of Set.values ()) { 3   Console.log ( num);  4   5  6  let map = new  map ([[' Name ', ' Ghostwu '], [' Age ', 22 7   (    Let detail of map.values ()) { 8   Console.log (detail);  9 } 

 1  let set = new  set ([Ten, 30 ] ); 2   ( Let num of Set.keys ()) { 3   Console.log (num ); 4   5  6  let map = new  map ([[' Name ', ' Ghostwu '], [' Age ', 22 7   ( Let detail of Map.keys ()) { 8   Console.log ( detail);  9 } 

Default iterator:

1Let userlist = [' Ghostwu ', ' Goku ', ' eight commandments ' ];2 3 //equivalent to calling values4  for(let name of UserList) {5 Console.log (name);6 }7 8Let set =NewSet ([10, 20, 30 ] );9 //equivalent to calling valuesTen  for(let num of Set) { One console.log (num); A } -  -Let map =NewMap ([[' Name ', ' GHOSTWU '], [' Age ', 22 ] ] ); the //equivalent to calling entries -  for(let detail of map) { - console.log (detail); -}

The default behavior of map can be abbreviated by deconstruction:

1 New Map ([[' Name ', ' GHOSTWU '], [' Age ',] ]); 2  for (Let [key, value] of map) {3     console.log (key  + '---> ' + value); 4 }

Using the expand operator to convert set and map to an array

1Let set =NewSet ([10, 20, 30 ] );2Let arr =[... set];3Console.log (arr);//[10,20,30]4 5Let map =NewMap ([[' Name ', ' GHOSTWU '], [' Age ', 22 ] ]);6Console.log ([... map]);//[ [' Name ', ' GHOSTWU '], [' Age ', []]7 8Let arr1 = [10, 20, 30 ];9Let arr2 = [' Ghostwu ', ' Eight Commandments ', ' Goku ' ];TenLet combine = [... arr1, ... arr2, ' done ' ]; OneConsole.log (combine);//[Ten, A, " Ghostwu", "Eight Commandments", "Goku", "Done")

[JS Master Road] ES6 series Tutorials-iterators, generators, For...of,entries,values,keys, etc.

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.