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