JavaScript learning Diary 5 map and set

Source: Internet
Author: User

Map

Is the structure of a set of key-value pairs with extremely fast lookup speeds.

For example: Find students ' grades, normal Arry array operations Create two ordinary Arry

var name = {' aaaa ', ' bbbb ', ' CCCC '};

var scores = {96,97,98}

Given a name, to find the corresponding score, first to find the corresponding position in the names, and then remove the corresponding results from scores, the longer the array, the longer the time.

If you use map to achieve, only need a "name"-"score" of the table, directly based on the name of the results, no matter how large the table, the search speed will not be slow. Write a map with JavaScript as follows:

1 var m = new Map ([[' AAA ', 96],[' BBB ', 97],[' CCC ', 98]); 2 m.get (' aaa ') //

Map has the following methods of operation

1 varm =NewMap ();2M.set (' AAA ', 67);//add a new Key-value;3M.get (' AAA ')// the4M.set (' BBB ', 67) ; 5M.has (' BBB ');//is there a key ' BBB ': true6M.Delete(' BBB ');//remove key ' BBB '7 8 a key can only correspond to one value, so, multiple times a key is placed in value, and the value below will flush the previous value:9 varm =NewMap ();TenM.set (' A1 ', 67) ; OneM.set (' A1 ', 68) ; AM.get (' A1 ');// the

Set

Setand Map similar, is also a set of keys, but does not store value. Since key cannot be duplicated, therefore, Set there is no duplicate key in the.

Repeating elements are Set automatically filtered in:

 1 var s = new Set([1, 2, 3, 3, ‘3‘]); 2 s; // Set {1, 2, 3, "3"} 

Note that numbers 3 and strings ‘3‘ are different elements.

add(key)you can add elements to a method by adding them Set repeatedly, but with no effect:

1  S.add (4); 2 s; 3 {1, 2, 3, 4}; 4 S.add (4); 5 s; 6 {1, 2, 3, 4};

delete(key)You can delete an element by means of:

1 var New Set ([1, 2, 3]); 2 // Set {1, 2, 3} 3 S.Delete(3); 4 // Set {1, 2}

JavaScript learning Diary 5 map and set

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.