Skip to content

Instantly share code, notes, and snippets.

console.log (map.get ("string")); // I'm a string
console.log (map.get (object)); // I am an object
console.log (map.get (function)); // I am a function
var map = new Map ();
mapa.set ('um', 1);
mapa.set ('two', 2);
mapa.set ('three', 3);
for (var key of mapa.keys ()) {
 console.log (key); // one two Three
}
for (var value of mapa.values ​​()) {
 console.log (value); // 1 2 3
}
var weakMap = new WeakMap ();
var element1 = window;
var element2 = document.querySelector ('body');
weakMap.set (element1, 'I am element1');
weakMap.set (element2, 'I am element2');
At this time, when we retrieve the values ​​through the keys, we will get the expected result:
console.log (weakMap.get (element1));
console.log (weakMap.get (element2));
// output
// I am element1
var weakMap = new WeakMap ();
function function () {};
var object = {};
// TypeError: Invalid value used as weak map key
weakMap.set ("string", "this is a string");
weakMap.set (function, "this is a function");
weakMap.set (object, "this is an object");
var Person = (function () {
var dataPrivate = new WeakMap ();
function Person (name) {
 PrivateData.set (this, {name: name});
}
Person.prototype.getName = function () {
 return dataPrivate.get (this) .name;
};
return Person;
} ());
function Set () {
 var array = [];
 this.add = function (value) {
 if (array.indexOf (value) === -1) {
 array.push (value);
 }
 }
}
function Set () {
 var array = [];
 this.add = function (value) {
 if (array.indexOf (value) === -1) {
 array.push (value);
 }
 },
this.showValues ​​= function () {
 console.log (array);
 }
var set = new Set ();
set.add (2);
set.add (1);
set.add (2);
set.showValues(); // [2,1]
var set = new Set ();
set.add (2);
set.add (1);
set.add (2);
for (const value of set) {
 console.log (value); // 2, 1
}
var set = new Set ([2,1,2]);
for (const value of set) {
 console.log (value); // 2, 1
}