JavaScript learns to record Day4-map, set, and iterable

Source: Internet
Author: User
Tags iterable new set

JavaScript learns to record Day4-map, set, and iterable

[TOC]

The default object representation of JavaScript {} can be thought of as a Map data structure in another language Dictionary , or a set of key-value pairs.

But the JavaScript object has a small problem, which is that the key must be a string. But actually number or other data type as a key is also very reasonable.

To solve this problem, the latest ES6 specification introduces new data types Map . To test whether your browser supports the ES6 specification, execute the following code and if the browser Referenceerror error, you need to change to a browser that supports ES6:

‘use strict‘;var m = new Map();var s = new Set();console.log(‘你的浏览器支持Map和Set!‘);
1. Map

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

For example, suppose you want to find the corresponding score according to the name of the classmate, if you use an array, you need two arrays:

var names = [‘Michael‘, ‘Bob‘, ‘Tracy‘];var scores = [95, 75, 85];

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:

var m = new Map([[‘Michael‘, 95], [‘Bob‘, 75], [‘Tracy‘, 85]]);m.get(‘Michael‘); // 95

Similar to a dictionary in Python, it's just a different notation.

Initializing a map requires a two-dimensional array, or directly initializing an empty map. Map has the following methods:

var m = new Map(); // 空Mapm.set(‘Lucy‘, 99); // 添加新的key-valuem.set(‘Lily‘, 89);console.log(m.has(‘Lucy‘)); // 是否存在key ‘Lucy‘: trueconsole.log(m.get(‘Lily‘)); // 89m.delete(‘Lily‘); // 删除key ‘Lily‘console.log(m.get(‘Lily‘)); // undefined

Since a key can only correspond to one value, the value is placed multiple times for a key, and the following values will flush the previous value out:

var m = new Map();m.set(‘Lily‘, 89);m.set(‘Lily‘, 99);console.log(m.get(‘Lily‘));  // 99
2. Set

A set is similar to a map and is a set of keys, but does not store value. Because key cannot be duplicated, there is no duplicate key in set.

To create a set, you need to provide an array as input, or create an empty set directly:

var s1 = new Set();  // 空Setvar s2 = new Set([1, 2, 3]);  // 含1, 2, 3

Repeating elements are automatically filtered in set:

var s = new Set([1, 2, 3, 3, "3"]);console.log(s);  

<font color= "Red" > Note </font>
The number 3 and the string ' 3 ' are different elements.

You can add elements to the set by using the Add (key) method, and you can add them repeatedly, but without effect:

s.add(4);console.log(s);  // Set {1, 2, 3, 4}s.add(4);console.log(s);  // 仍然是 Set {1, 2, 3, 4}

You can delete an element by using the Delete (key) method:

var s = new Set([1, 2, 3]);console.log(s);  // Set {1, 2, 3}s.delete(3);console.log(s);  // Set {1, 2}
3. iterable

Traversal Array can take the subscript loop, traverse Map and Set cannot use subscript. In order to unify collection types, the ES6 standard introduces new iterable types Array , Map and Set all of them belong to iterable types.

A iterable collection with a type can traverse through a new for ... of loop.

for ... ofThe loop is the new syntax introduced by ES6, please test whether your browser supports:

‘use strict‘;var a = [1, 2, 3];for (var x of a) {}console.log(‘你的浏览器支持for ... of‘);

What is the difference between the for ... of loops and for ... in loops?

for ... inThe loop is actually a property name of the object that is traversed because of historical problems. An Array array is actually an object, and its index of each element is treated as an attribute.

When we manually Array add extra attributes to an object, the for ... in loop brings unexpected unintended effects:

var a = [‘A‘, ‘B‘, ‘C‘];a.name = ‘Hello‘;for (var x in a) {    console.log(x); // ‘0‘, ‘1‘, ‘2‘, ‘name‘}

for ... inLoops will be name included, but Array the length attributes are not included.

for ... ofLoops completely fix these problems by looping only the elements of the collection itself:

var a = [‘A‘, ‘B‘, ‘C‘];a.name = ‘Hello‘;for (var x of a) {    console.log(x); // ‘A‘, ‘B‘, ‘C‘}

This is why you should introduce a new for ... of loop.

However, a better approach is to use the built-in iterable forEach method directly, which receives a function that automatically callbacks the function each time it iterates. Take Array for example:

‘use strict‘;var a = [‘A‘, ‘B‘, ‘C‘];a.forEach(function (element, index, array) {    // element: 指向当前元素的值    // index: 指向当前索引    // array: 指向Array对象本身    console.log(element + ‘, index = ‘ + index);});

Results:

A, index = 0B, index = 1C, index = 2

<font color= "Red" > Note </font>:
forEach()method is introduced by the ES5.1 standard and you need to test whether the browser supports it.

SetArraysimilar but Set no index, so the first two parameters of the callback function are the elements themselves:

var s = new Set([‘A‘, ‘B‘, ‘C‘]);s.forEach(function (element, sameElement, set) {    console.log(element);});

Results:

ABC

MapThe callback function parameters are sequentially value , key and map themselves:

var m = new Map([[1, ‘x‘], [2, ‘y‘], [3, ‘z‘]]);m.forEach(function (value, key, map) {    console.log(value);});

Results:

xyz

If you are not interested in certain parameters, they can be ignored because JavaScript function calls do not require parameters to be consistent. For example, you only need to obtain Array element :

var a = [‘A‘, ‘B‘, ‘C‘];a.forEach(function (element) {    console.log(element);});

Results:

ABC

Learning Reference Tutorial: http://www.liaoxuefeng.com

JavaScript learns to record Day4-map, set, and iterable

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.