Skip to content

Instantly share code, notes, and snippets.

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 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 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
}
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 ();
function function () {};
var object = {};
map.set ("string", "I'm a string");
map.set (object, "I am an object");
map.set (function, "I am a function");
var iterator = witches [Symbol.iterator] ();
var done = false;
var next = iterator.next ();
of {
 var wizard = next.value;
 hatSelectorMakeHouseSelection (wizard);
 next = iterator.next ();
} while (! next.done);
Assuming that the doSelectionDomain method displays on the console the student's name and their home, using our list of wizards from the previous example in this algorithm, we have as output:
student: Harry Potter | House: Gryffindor
var witches = ['Harry Potter', 'Hermione Granger', 'Ron Weasley'];
// get the iterator
var iteratorWitches = witches [Symbol.iterator] ();
iteratorWow.next (); // {value: Harry Potter, done: false}
iteratorWow.next (); // {value: Hermione Granger, done: false}
iteratorWow.next (); // {value: Ron Weasley, done: false}
iteratorWow.next (); // {value: undefined, done: true}
var students = [
 {name: 'adam', age: 10},
 {name: 'brian', age: 20},
 {name: 'charles', age: 30}
];
var names = students.reduce (function (arrayNames, student) {
 arrayNames.push (student.name);
 return array Names;
}, []);
console.log (names); // ['adam', 'brian', 'charles']
var numbers = [1,2,3,4,5];
var sum = 0;
sum = numbers.reduce (function (sum, number) {
 return sum + number;
}, 0)
console.log (sum); // 15
var numbers = [1,2,3,4,5];
var sum = 0;
for (var i = 0; i <numbers.length; i ++) {
 sum + = numbers [i];
}
console.log (sum); // 15