Es6 notes 5 ^_^ set, map, iterator, es6iterator

Source: Internet
Author: User
Tags map data structure java iterable

Es6 notes 5 ^_^ set, map, iterator, es6iterator
I. set1. basic usage

The data structure Set is similar to an array, but the Member values are unique without repeated values.
Let s = new Set (); [2, 3, 5, 4, 5, 2]. map (x => s. add (x) for (let I of s) {console. log (I)} // 2 3 5 4 // The Set function accepts an array as a parameter for initialization. Var items = new Set ([1, 2, 3, 4, 5, 5]); console. log (items); // set object console. log (items. size); // 5 // when a value is added to the Set, no type conversion occurs, so 5 and 5 are two different values. Let set = new Set (); set. add ({}) console. log (set. size); // 1 set. add ({}) console. log (set. size); // 2 // The code above indicates that the two empty objects are considered as two values because they are not exactly equal.
2. Set instance attributes
An instance of the Set structure has the following attributes.
Set. prototype. constructor: constructor. The default value is Set function.
Set. prototype. size: Total number of members of the Set instance.
Let s = new Set (); s. add (1 ). add (2 ). add (2); // note that 2 is added to the console twice. log (s); console. log (s. size); // 2
3. Set instance method
There are two main categories:
Operation Methods (used to operate data) and traversal methods (used to traverse members ). The following describes four operations.
Add (value): add a value and return the Set structure itself.
Delete (value): delete a value. A boolean value is returned, indicating whether the deletion is successful.
Has (value): returns a Boolean value indicating whether the value is a member of the Set.
Clear (): clear all members without returning values.
Examples of these attributes and methods are as follows:
Let s = new Set (); s. add (1 ). add (2 ). add (2); console. log (s. has (1); // true console. log (s. has (2); // true console. log (s. has (3); // false s. delete (2); console. log (s. has (2); // false s. clear (); console. log (s. size); // 0 // Array. the from method can convert the Set structure into an array: let items = new Set ([1, 2, 3, 4, 5]); let Array = array. from (items); console. log (array); // [1, 2, 3, 4, 5]
4. Traversal
An instance of the Set structure has four traversal methods, which can be used to traverse members.
Keys (): returns a traversal tool with a key name.
Values (): returns a traversal of key values.
Entries (): returns the traversal of a key-value pair.
ForEach (): Use the callback function to traverse each member.
Because the Set structure has no key name and only the key value (or the key name and key value are the same), the behavior of the key method and the value method is completely consistent.
    let set = new Set(['red', 'green', 'blue']);    for ( let item of set.keys() ){        console.log(item);// red green blue    }    for ( let item of set.values() ){        console.log(item);// red green blue    }    for ( let item of set.entries() ){        console.log(item);// ["red", "red"]  ["green", "green"] ["blue", "blue"]    }    set.forEach(function(item){        console.log(item);// red green blue    })
Ii. WeakSet
WeakSet and Set do not store duplicate elements, but there are some differences.
WeakSet members can only be objects, but not other types of values.
The WeakSet structure has the following three methods.
WeakSet. prototype. add (value): add a new member to the WeakSet instance.
WeakSet. prototype. delete (value): clears a specified Member of the WeakSet instance.
WeakSet. prototype. has (value): returns a Boolean value indicating whether a value exists in
Let ws = new WeakSet (); // console. log (ws. add (1); // TypeError: Invalid value used in weak set let obj ={}; let foo ={}; ws. add (window); ws. add (obj); console. log (ws); console. log (ws. has (window); // true console. log (ws. has (foo); // false ws. delete (window); console. log (ws. has (window); // false // WeakSet has no size attribute and cannot traverse its members. Console. log (ws. size) // undefined console. log (ws. forEach); // undefined // ws. forEach (function (item) {console. log ('weakset has' + item)}) // TypeError: undefined is not a function
Iii. Purpose and basic usage of Map Structure
Map is a "super object". Its key can be of the String type and other types (such as objects)
His method is similar to Set:
Size: Total number of returned Members.
Set (key, value): set a key-value pair.
Get (key): Read a key.
Has (key): returns a Boolean value indicating whether a key is in the Map data structure.
Delete (key): delete a key.
Clear (): clear all members.
        let m = new Map();        o = {p: "Hello World"};        m.set(o, "content")        console.log(m);        console.log(m.get(o))// "content"
Instance attributes and operation methods
Map Structure instances have the following attributes and operation methods.
Size: Total number of returned Members.
Set (key, value): set the key value corresponding to the key, and then return the entire Map structure. If the key already has a value, the key value is updated. Otherwise, the key is generated.
Get (key): reads the key value corresponding to the key. If the key cannot be found, undefined is returned.
Has (key): returns a Boolean value indicating whether a key is in the Map data structure.
Delete (key): deletes a key and returns true. If the deletion fails, false is returned.
Clear (): clear all members without returning values.
The set () method returns the Map itself, so you can use the chained method.
Let map = new Map (). set (1, 'A '). set (2, 'B '). set (3, 'C'); console. log (map); // The following are examples of has () and delete. Let m = new Map (); m. set ("edition", 6) // The key is a string m. set (262, "standard") // The Key is m. set (undefined, "Hannah") // The Key is undefined let hello = function () {console. log ("hello");} m. set (hello, "Hello ES6! ") // The key is the function m. has ("edition") // true m. has ("years") // false m. has (262) // true m. has (undefined) // true console. log (m. get (undefined); m. has (hello) // true m. delete (undefined) m. has (undefined) // false m. get (hello) // Hello ES6! M. get ("edition") // 6 // The following is an example of the size attribute and the clear method. Map. set ('foo', true); map. set ('bar', false); map. size // 2 map. clear () map. size // 0 console. log (Array. from (m); // Array
Traversal method
Map native provides three traversal devices.
Keys (): The traversal tool of the Return key name.
Values (): The iterator that returns the key value.
Entries (): returns the traversal of all members.
Example:
Let map = new Map ([['F', 'no'], ['T', 'yes'],]); for (let key of map. keys () {console. log (key);} // "F" // "T" for (let value of map. values () {console. log (value);} // "no" // "yes" for (let item of map. entries () {console. log (item [0], item [1]);} // "F" "no" // "T" "yes" // or for (let [key, value] of map. entries () {console. log (key, value);} // equivalent to map. entries () for (let [key, value] of map) {console. log (key, value );}
The Map structure is converted into an array structure. A quick method is to use the extension operator (...).
Let map = new Map ([[1, 'one'], [2, 'two'], [3, 'three ']); [... map. keys ()]; // [1, 2, 3] [... map. values ()]; // ['one', 'two', 'three '] [... map. entries ()]; // [[1, 'one'], [2, 'two'], [3, 'three '] [... map] // [[1, 'one'], [2, 'two'], [3, 'three '] // In addition, Map has a forEach method, similar to the forEach method of an array, you can also traverse the array. Map. forEach (function (value, key) {console. log (key + ':' + value );});
4. WeakMap
The WeakMap structure is similar to the Map structure. The only difference is that it only accepts the object as the key name (except null) and does not accept the original type as the key name, the object to which the key name points is not included in the garbage collection mechanism. Set () and get () are used to add data and obtain data respectively:
Let map = new WeakMap (); let element ={}; map. set (element, "Original"); // let value = map can be used below. get (element); console. log (value); // "Original"
There are two main differences between WeakMap and Map in API:
First, there is no traversal operation (that is, there is no key (), values (), and entries () methods), and there is no size attribute;
Second, the clear method is not supported. This is related to the reason that the WeakMap key is not included in the reference and ignored by the garbage collection mechanism.
Therefore, WeakMap has only four methods available: get (), set (), has (), and delete ().
5. Iterator Concept
Iterator is a unified interface mechanism to process all different data structures.
Iterator has three functions:
1. provides a unified and simple access interface for various data structures;
Second, the members of the data structure can be arranged in a certain order;
Third, ES6 creates a new traversal command for... of loop. The Iterator interface is mainly used for... of consumption.
The Iterator traversal process is like this.
Create a pointer pointing to the starting position of the current data structure. That is to say, the returned value of the traversal is a pointer object.
When you call the next method of the pointer object for the first time, you can point the pointer to the first member of the data structure.
When the next method of the pointer object is called for the second time, the Pointer Points to the second member of the data structure.
Call the next method of the pointer object until it points to the end position of the data structure.
Each call to the next method returns the information of the current member. Specifically, an object containing the values and done attributes is returned. The value attribute is the value of the current member, and the done attribute is a Boolean value, indicating whether the traversal ends.
    function idMaker(){        var index = 0;        return {            next: function(){                return {value: index++, done: false};            }        }    }    let it = idMaker();    console.log(it.next().value); // '0'    console.log(it.next().value); // '1'    console.log(it.next().value); // '2'
Default Iterator interface for Data Structure
In ES6, a method named Symbol. iterator must be implemented to iterate data structures (such as arrays). This method returns an iterator for the structure element. Note that Symbol. iterator is a Symbol, which is the new original value type added to es6.
    let arr = ['a', 'b', 'c'];    let iter = arr[Symbol.iterator]();    console.log(iter);    console.log(iter.next()); // { value: 'a', done: false }    console.log(iter.next()); // { value: 'b', done: false }    console.log(iter.next()); // { value: 'c', done: false }    console.log(iter.next()); // { value: undefined, done: true }
In the code above, the variable arr is an array, and the Native has a traversal interface, which is deployed on the Symbol. iterator attribute of arr. Therefore, call this attribute to obtain the traversal tool.
Call the default Iterator Interface
In some cases, the iterator interface (the Symbol. iterator method) is called by default. In addition to the for... of loop described below, there are several other occasions.
Deconstruct assignment
The iterator interface is called by default when the array and Set structure are reconstructed and assigned values.
Let set = new Set (). add ('A '). add ('B '). add ('C'); let [x, y] = set; // x = 'a'; y = 'B' let [first ,... rest] = set; console. log (first); // 'A' console. log (rest); // ['B', 'C']; // extension operator (...) the default iterator interface is also called. // Example 1 let str = 'hello'; console. log ([... str]); // ['h', 'E', 'l', 'l', 'O'] // Example 2 let arr = ['B ', 'C']; console. log (['A ',... arr, 'D']); // ['A', 'B', 'C', 'D']
Other scenarios
The default iterator interface is also used in the following scenarios. For more information, see the relevant sections.
Yield *
Array. from ()
Map (), Set (), WeakMap (), WeakSet ()
Promise. all (), Promise. race ()

Native Data Structure with Iterator Interface
A string is an object similar to an array and also has an Iterator interface.
Let someString = "hi"; typeof someString [Symbol. iterator] // "function" let iterator = someString [Symbol. iterator] (); iterator. next () // {value: "h", done: false} iterator. next () // {value: "I", done: false} iterator. next () // {value: undefined, done: true} // In the above Code, call Symbol. the iterator method returns a traversal tool that can call the next method to traverse strings. // Override the native Symbol. iterator method to modify the traversal behavior. Let str = new String ("hi ");[... str] // ["h", "I"] str [Symbol. iterator] = function () {return {next: function () {if (this. _ first) {this. _ first = false; return {value: "bye", done: false };}else {return {done: true }}, _ first: true };}; [... str] // ["bye"] str // "hi" // In the above Code, the Symbol of the string str. the iterator method is modified, so the extension operator (...) the returned value is bye, while the string itself is still hi.
Vi. Iterator interface and Generator Function

The simplest implementation of the Symbol. iterator method is to use the Generator function described in the next chapter.
Let myIterable ={}; myIterable [Symbol. iterator] = function * () {yield 1; yield 2; yield 3 ;}; console. log (myIterable); console. log ([... myIterable]); // [1, 2, 3] // or use the following simple Syntax: let obj = {* [Symbol. iterator] () {yield 'hello'; yield 'World' ;}}; for (let x of obj) {console. log (x); // hello world} // In the above Code, Symbol. the iterator method almost does not need to deploy any code. You only need to use the yield command to return values for each step.
Return () and throw () of the traversal Server ()
In addition to the next method, the pointer object returned by the traversal tool can also have the return method and throw method. The next method must be deployed, and the return and throw methods are optional.
The return method is called if the for... of loop exits early (usually because of an error, or a break or continue Statement.
If you need to clear or release resources before traversing an object, you can deploy the return method.
The throw method is mainly used with the Generator function. This method is not used by the general traversal tool.
7. for... of Loop
The iterator object allows you to customize the iterator like CLI IEnumerable or Java Iterable.
Convert for .. in to a custom iterator-based iteration, such as for .. of. You do not need to implement an array and support the same inert design pattern as LINQ.
    let fibonacci = {        [Symbol.iterator]() {            let pre = 0, cur = 1;            return {                next() {                    [pre, cur] = [cur, pre + cur];                    return { done: false, value: cur }                }            }        }    }    console.log(fibonacci);    for (let n of fibonacci) {        // truncate the sequence at 1000        if (n > 1000){            break;        }        console.log(n);    }

This article is to be continued ......










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.