Przejdź do treści głównej
← ⚡ JavaScript & the browser·Moduł C6 · Lekcja 2
ZadanieBuild counts as a Map from name to int starting at {anna:3, bob:5}. Increment anna by 2. Log size, then log each "<name>: <count>" line. Then make tags = Set(['js','ts','js','go']) and log its size.

Iterating Maps and Sets

100 XP8 min
Teoria

Map vs Object

A Map lets keys be any value (not just strings). Maps preserve insertion order, iterate cleanly, and have a true .size.

const counts = new Map();
counts.set("anna", 3);
counts.set("bob",  5);

for (const [key, value] of counts) {
  console.log(key + ": " + value);
}
// anna: 3
// bob: 5

Default iteration on a Map yields [key, value] pairs. You can also call .keys(), .values(), or .entries() explicitly.

Set — unique values

A Set is a unique collection. Iterates in insertion order.

const tags = new Set(["js", "ts", "js"]);
console.log(tags.size); // 2
for (const tag of tags) console.log(tag); // "js", "ts"

When to reach for Map / Set

  • Counting unique items → Set.
  • Tracking last-seen timestamp per user → Map with user id as key.
  • Order matters and you need O(1) lookup → Map beats searching arrays.
🔒

Zarejestruj się, aby zacząć kodować

Teoria jest dostępna dla każdego. Edytor, podgląd na żywo i check odblokowują się z 7-dniowym darmowym okresem próbnym — wymagana karta, anuluj w dowolnym momencie.

Zarejestruj się — darmowy okres próbny →

Pierwsze 10 lekcji w każdej ścieżce jest darmowych. Karta nie jest wymagana.

← PoprzedniaNastępna lekcja →

Codziennie jedna wskazówka Python lub web — na maila

Krótko, ręcznie pisane, bez spamu. Wypisanie w jedno kliknięcie.