JavaScript Map 和 Set

in conclusion

  • Map: Store key-value pairs, different Object, key can be any value.
  • Set: Do not store duplicate values

Map

Stored 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:

1 '1'
3 '3'
2 '2'
foo bar

Any value, the original value or an object, can be used as Mapa key.

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 Object, no requirement for addition to the key value may be used as an outer, Mapcarrying walker (Iterator), use may be made thereto for ofstatement.

It also comes with a number of convenient properties and methods, such as size, clear().

Set

The 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);
}

输出:

4
true
true
1
2
foo
{ a: 1, b: 2 }

相关资源

Guess you like

Origin www.cnblogs.com/Wayou/p/javascript_map_and_set.html