Home >Web Front-end >JS Tutorial >Detailed explanation of Map and Set instances in JavaScript

Detailed explanation of Map and Set instances in JavaScript

零下一度
零下一度Original
2017-06-26 10:12:091298browse

Map

Map is a structure of key-value pairs, which has extremely fast search speed.

Definition of Map.

//空map设值key-valuevar m = new Map();
m.set("XiaoMing",99);
m.set("XiaoHong",66);//构造参数传key-valuevar m = new Map([['XiaoMing', 99], ['XiaoHong', 66]]);

Methods in Map

var m = new Map(); // 空Mapm.set('XiaoMing', 99); // 添加新的key-valuem.has('XiaoMing'); // 是否存在key 'XiaoMing': truem.get('XiaoMing'); // 99m.delete('XiaoMing'); // 删除key 'XiaoMing'm.get('XiaoMing'); // undefined

If you repeatedly set a value for a key, the subsequent value will overwrite the previous value.

var m = new Map();
m.set('XiaoMing', 99);
m.set('XiaoMing', 98);
m.get('XiaoMing'); // 98

Set

# Set is similar to Map, but set stores keys and the keys are not repeated.

Creation of Set.

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

Insert duplicate values, set will filter the duplicate values

 s =  Set([1, 2, 33>>s; s.delete(3);
>>s;

Map and Set traversal

Array can use subscripts for loop traversal, but Map and Set cannot use subscripts. In order to unify collection types, the ES6 standard introduced the iterable type. Array, Map, and Set all belong to the iterable type.

Collections with type iterable can be traversed via a new for ... of loop.

var a = ['A', 'B', 'C'];var s = new Set(['A', 'B', 'C']);var m = new Map([[1, 'x'], [2, 'y'], [3, 'z']]);for (var x of a) { // 遍历Array    alert(x);
}for (var x of s) { // 遍历Set    alert(x);
}for (var x of m) { // 遍历Mapalert(x[0] + '=' + x[1]);
}

Better traversal: forEach

##forEach is a built-in method of iterable, which receives a function. This function is automatically called back every iteration.

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

Set is similar to Array, but Set has no index, so the first two parameters of the callback function are Is the element itself:

var s = new Set(['A', 'B', 'C']);
s.forEach(function (element, sameElement, set) {
    alert(element);
});
The callback function parameters of

Map are value, key and map Self:

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

The above is the detailed content of Detailed explanation of Map and Set instances in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn