1. Iterator
Iterator
It is a new traversal mechanism introduced by ES6. Two cores
- Iterator is a unified interface, its function is to enable various data structures to be easily accessed, it is done by a key
to implement the method.
- An iterator is a pointer used to traverse data structure elements (such as a cursor in a database).
// Use iteration// 1. Create an iterator usingconst items = ['one','a','b']; const it = items[](); (it);// Array Iterator{} // 2. Call next() method and iterate downward, next() returns the current positionconst nx = (); // 3. When done is true, the traversal ends.(nx); // {value: 'one', done: false}
Iterable data structureArray
,String
,Map
,Set
;
Note: Objects cannot use iteration, and it is closely related to iteration.for..of
cycle.
Convert objects to arrays using relatedfor..of
cycle.
// Convert object to arrayconst arrlink = {"length":3,0:"zero","1":"one"};// Note that the first item is the length of the declared array. If there is no first item, it is an empty array((arrlink)); // (3) ['zero', 'one', undefined] The length of the input parameter should be removed and the default value bit is exceeded.for (let item of (arrlink)){ (item);// The result of the traversal is zero , one , undefined object's value.}
2. Generator
ES6 has been newly introducedGenerator
Functions, can be passed through keywordsyield
Stop the function flow (similar to the generator in Python).
It provides the possibility to change the execution process, and thus also provides a solution for asynchronous programming (similar to the use of this function to implement coroutines in Python).
Distinguishing from ordinary functions:
- exist
function
After that, there is a function name before*
; - There is inside the function
yield
(Output) Expression.
// Pay attention to the format The function keyword is followed by *function* func(a){ ("one"); yield a; ("two"); yield 2; ("three"); return 3; } // Every time the function is executed, a traverser object will be returnedlet fn = func(1); (fn);// func{<suspended>} // The next() method of the traverser must be called to move the pointer down to the next state.(());// {value: 1, done: false} (());// {value: 2, done: false} (());// {value: 3, done: true} (());// {value: undefined, done: true}
Summarize:Generator
Functions are executed in segments.yield
The statement is to pause execution.next
The method can be resumed.
function* add() { ('start'); let x = yield '2'; ('one:' + x);//20 let y = yield '3'; ('two:' + y);//30 ('total:' + (x + y));// 50 return x+y; } var a = add(); ((10)); ((20)); ((30)); // ((100));
return
The method returns the given value and ends the traversalGenerator
function. Provides the returned parameter, returns the specified value, does not provide, returnsundefined
.
//Usage scenarios, traversal operations are provided for objects that do not have Interator interfacefunction* objectEntries(obj) { // Get all keys of the object and store them in an array const propKeys = (obj); // (propKeys); for (const propKey of propKeys) { yield [propKey, obj[propKey]]; } } const obj = { name: 'Jane', age: 18 } obj[] = objectEntries; (obj); for (const [key, value] of objectEntries(obj)) { (`${key}: ${value}`); }
Generator application:
// ajax is a typical asynchronous operation. Ajax operation can be deployed through the Generator function, which can be expressed in a synchronous mannerfunction* main() { const res = yield request( '/s6/weather/now?location=beijing&key=4693ff5ea653469f8bb0c29638035976' ); (res); ('1111'); } let it = main(); () // /s6/weather/now?location=beijing&key=4693ff5ea653469f8bb0c29638035976 function request(url) { // Assumption $.ajax({ url, method: 'get', success(res) { // (res); (res); } }) } // Generator function is used to handle asynchronous operationsfunction* load() { loadUI(); yield showData(); hideUI(); } let itLoad = load(); // (itLoad); // The first call will display the loading UI interface and load data asynchronously(); function loadUI() { ('Loading loading interface...'); } function showData(){ setTimeout(() => { ('Data loading is complete...'); // The second call will call hideUI() and hide Loading (); }, 1000); } function hideUI() { ('Hide loading....'); } // Deploy to any objectInteratorinterface
This is the end of this article about detailed explanation of iterators and generators in ES6. For more related ES6 iterators and generators, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!