in conclusion
MapStored key-value pair with the same intervening sequence read. var map = new Map([[1, "1"], [3, "3"], [2, "2"]]);
map.set("foo", "bar");
for (const [key, val] of map) {
console.log(key, val);
}
Output: Any value, the original value or an object, can be used as var myMap = new Map();
var keyString = 'a string',
keyObj = {},
keyFunc = function() {};
// setting the values
myMap.set(keyString, "value associated with 'a string'");
myMap.set(keyObj, 'value associated with keyObj');
myMap.set(keyFunc, 'value associated with keyFunc');
myMap.size; // 3
// getting the values
myMap.get(keyString); // "value associated with 'a string'"
myMap.get(keyObj); // "value associated with keyObj"
myMap.get(keyFunc); // "value associated with keyFunc"
myMap.get('a string'); // "value associated with 'a string'"
// because keyString === 'a string'
myMap.get({}); // undefined, because keyObj !== {}
myMap.get(function() {}); // undefined, because keyFunc !== function () {}
Comparison It also comes with a number of convenient properties and methods, such as SetThe only value is stored for duplicate values are ignored. Example: var obj = { a: 1, b: 2 };
var set = new Set([1, 2, 2, "foo"]);
set.add(obj);
set.add(obj);
console.log("size:", set.size);
console.log(set.has(2));
console.log(set.has(obj));
for (const val of set) {
console.log(val);
}
输出: 相关资源 |
JavaScript Map 和 Set
Guess you like
Origin www.cnblogs.com/Wayou/p/javascript_map_and_set.html
Recommended
Ranking