Introduction to Maps in JavaScript - Lee-hyuna/33-js-concepts-kr GitHub Wiki
Introduction to Maps in JavaScript
λ²μ : https://alligator.io/js/maps-introduction/
μ°λ¦¬λ μμ Javascript μ sets μ μ€λͺ νμλ€. κ·Έκ²μ ES2015μμ μκ°νλ maps κ΄ν ν λ‘ μ μ΄μΌκΈ° νλ λ Όλ¦¬λ₯Ό λ°λ¦ λλ€. Maps λ€μ key-value μμ μ μ₯νλ μλ‘μ΄ νμ μ object μ΄λ€.
κ°μ²΄μ λ¬λ¦¬ map ν€λ κ°μ²΄ λλ κΈ°λ₯κΉμ§ λͺ¨λ μ νμ΄ λ μ μμ΅λλ€. λν mapμ μ¬μ΄μ¦λ₯Ό κ°μ²΄λ§νΌ κ°λ¨νμ§ μμ§λ§ μ½κ² μ»μ μ μμ΅λλ€. λν mapμ μ¬μ©νλ©΄ μμμ λν 보μ₯μ΄ μλ κ°μ²΄μ λ¬λ¦¬ κ°μ΄ μΆκ° λ μμλλ‘ λ°λ³΅ ν μ μμ΅λλ€.
λ€μμ set, get, size, has, delete λ° clearμ κ°μ λͺ κ°μ§ μ¬μ© κ°λ₯ν λ°©λ² λ° μμ±μ 보μ¬μ£Όλ κ°λ¨ν map μμ λλ€.
let things = new Map();
const myFunc = () => 'π';
things.set('π', 'Car');
things.set('π ', 'House');
things.set('βοΈ', 'Airplane');
things.set(myFunc, 'π Key is a function!');
things.size; // 4
things.has('π'); // true
things.has(myFunc) // true
things.has(() => 'π'); // false, not the same reference
things.get(myFunc); // 'π Key is a function!'
things.delete('βοΈ');
things.has('βοΈ'); // false
things.clear();
things.size; // 0
// setting key-value pairs is chainable
things.set('π§', 'Wrench')
.set('πΈ', 'Guitar')
.set('πΉ', 'Joystick');
const myMap = new Map();
// Even another map can be a key
things.set(myMap, 'Oh gosh!');
things.size; // 4
things.get(myMap); // 'Oh gosh!'
Initializing Maps from Arrays
λΉμ μ λκ°μ§ valueλ₯Ό μ§λ arrayλ₯Ό ν¬ν¨ν arrayλ‘ λΆν° mapμ μ΄κΈ°ν ν μ μμ΅λλ€.
const funArray = [
['πΎ', 'Champagne'],
['π', 'Lollipop'],
['π', 'Confetti'],
];
let funMap = new Map(funArray);
funMap.get('πΎ'); // Champagne
Iterating Over Maps
forβ¦of and array destructuring λ₯Ό μ¬μ©νλ©΄ maps λ€μ μ½κ² μν ν μ μμ΅λλ€.
let activities = new Map();
activities.set(1, 'π');
activities.set(2, 'π');
activities.set(3, 'π£');
activities.set(4, 'π€Ύ');
for (let [nb, activity] of activities) {
console.log(`Activity ${nb} is ${activity}`);
}
// Activity 1 is π
// Activity 2 is π
// Activity 3 is π£
// Activity 4 is π€Ύ
...κ·Έλ¦¬κ³ λΉμ μ forEach λ₯Ό μ¬μ©ν΄μ mapμ λκ°μ λ°©λ²μΌλ‘ μν ν μ μμ΅λλ€. κ·Έλ¬λ forEach μ½λ°± ν¨μμ 첫 λ²μ§Έ μΈμλ κ° μ΄κ³ λ λ²μ§Έ μΈμλ ν€μ λλ€. λ€μμ **forβ¦ of ** μμ μ λμΌν κ²°κ³Όμ λλ€.
activities.forEach((value, key) => {
console.log(`Activity ${key} is ${value}`);
});