>  기사  >  웹 프론트엔드  >  JS 지도

JS 지도

WBOY
WBOY원래의
2024-07-19 15:06:58811검색

Map in JS

JavaScript의 맵은 키가 모든 유형일 수 있는 키-값 쌍의 모음입니다. 삽입 순서를 유지합니다. 즉, 항목이 추가된 순서대로 반복됩니다.

지도의 주요 특징

  1. 고유 키: 지도의 각 키는 고유합니다.
  2. 키의 모든 데이터 유형: 객체와 달리 키는 함수, 객체 또는 기본 유형을 포함한 모든 데이터 유형이 될 수 있습니다.
  3. 반복 가능: 의 키, 값 또는 항목을 반복할 수 있습니다.

기본 작업

지도 만들기

let funnyMap = new Map();

지도에 요소 추가

funnyMap.set('a', 1); // string key
funnyMap.set(2, 'two'); // number key
funnyMap.set(true, 'yes'); // boolean key
funnyMap.set({name: 'obj'}, 'object'); // object key

// Funny example
funnyMap.set('knock-knock', 'who’s there?');

지도에서 값 얻기

console.log(funnyMap.get('a')); // 1
console.log(funnyMap.get(2)); // two
console.log(funnyMap.get(true)); // yes

// Funny example
console.log(funnyMap.get('knock-knock')); // who’s there?

키 확인

console.log(funnyMap.has('a')); // true
console.log(funnyMap.has(42)); // false

// Funny example
console.log(funnyMap.has('chicken')); // false (It crossed the road)

요소 제거

funnyMap.delete('a');
console.log(funnyMap.has('a')); // false

// Funny example
funnyMap.delete('knock-knock');
console.log(funnyMap.get('knock-knock')); // undefined (No one answered)

지도 크기 얻기

console.log(funnyMap.size); // 3 after deletion

// Funny example
console.log(`The map has ${funnyMap.size} jokes left.`);

지도 지우기

funnyMap.clear();
console.log(funnyMap.size); // 0

// Funny example
console.log(`All jokes are cleared from the map.`);

지도 반복

...의 용도

funnyMap.set('banana', 'yellow');
funnyMap.set('apple', 'red');
funnyMap.set('grape', 'purple');

// Iterating over keys
for (let key of funnyMap.keys()) {
    console.log(`Key: ${key}`);
}

// Iterating over values
for (let value of funnyMap.values()) {
    console.log(`Value: ${value}`);
}

// Iterating over entries
for (let [key, value] of funnyMap.entries()) {
    console.log(`Key: ${key}, Value: ${value}`);
}

// Funny example
funnyMap.set('dad joke', 'What do you call fake spaghetti? An impasta!');
for (let [key, value] of funnyMap.entries()) {
    console.log(`Here’s a ${key}: ${value}`);
}

forEach 사용

funnyMap.forEach((value, key) => {
    console.log(`Key: ${key}, Value: ${value}`);
});

// Funny example
funnyMap.set('bad pun', 'I’m reading a book on anti-gravity. It’s impossible to put down!');
funnyMap.forEach((value, key) => {
    console.log(`Here’s a ${key}: ${value}`);
});

실제 용도

단어 세기(재미있는 버전)

농담 모음집에 특정 단어가 몇 번 나오는지 세고 싶다고 상상해 보세요.

let jokeText = "Why did the scarecrow win an award? Because he was outstanding in his field!";

// Splitting text into words
let words = jokeText.split(/\W+/);

let wordCount = new Map();

words.forEach(word => {
    word = word.toLowerCase();
    if (wordCount.has(word)) {
        wordCount.set(word, wordCount.get(word) + 1);
    } else {
        wordCount.set(word, 1);
    }
});

wordCount.forEach((count, word) => {
    console.log(`Word: ${word}, Count: ${count}`);
});

// Funny example
console.log('Word counts in our joke:');
wordCount.forEach((count, word) => {
    console.log(`"${word}": ${count} times`);
});

요약

JavaScript의 맵은 모든 데이터 유형의 키-값 쌍을 보유할 수 있고, 쉬운 반복 방법을 제공하며, 요소의 순서를 유지하는 다목적 데이터 구조입니다. 농담으로 단어를 세거나 다양한 수수께끼에 대한 응답을 저장하는 등 일반 객체보다 더 유연한 키 관리가 필요한 시나리오에 유용합니다.

위 내용은 JS 지도의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.