The map and set in JS

Source: Internet
Author: User
Tags new set

Using iterable built-in forEach methods

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

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) { alert(element);});

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) { alert(value);});

JS in the parameters do not require consistency, you can need a few write a few (of course, more than write is undefined, and parameter names can casually write "funny")

A.foreach (function (element, index, ARRAY,ADSF) {
Element: A value that points to the current element
Index: point to Current index
Array: points to the array object itself
Console.log (element, index, ARRAY,ADSF);
});
Vm2066:5 a 0 ["a", "B", "C"] undefined
Vm2066:5 B 1 ["A", "B", "C"] undefined
Vm2066:5 C 2 ["A", "B", "C"] undefined

For loop: Similar to foreach in Java:

for (var x of a) {    alert(x); // ‘A‘, ‘B‘, ‘C‘}

The default object representation of JS is {} Key-value pairs, but the keys are all strings, so the map is referenced

var m = new Map ([[' Micheal ', 99],[' Bob ', 90],[' Baobao ', 100]]);

M.get (' micheal ');

You can also do this:

var m = new Map(); // 空Map m.set(‘Adam‘, 67); // 添加新的key-value m.set(‘Bob‘, 59); m.has(‘Adam‘); // 是否存在key ‘Adam‘: true m.get(‘Adam‘); // 67 m.delete(‘Adam‘); // 删除key ‘Adam‘ m.get(‘Adam‘); // undefined

Set is similar to list in Java but the values are not duplicated and the types are changeable;

The Add method adds an element,

Set([1, 2, 3, 3, ‘3‘]);
S.add (4); S.delete (2);

The map and set in JS

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.