JS 地图
文章标签
地图
javascript 中的 map 是键值对的集合,其中键可以是任何类型。它保留插入的顺序,这意味着项目按照添加的顺序进行迭代。
地图的主要特征;
- 唯一键:地图中的每个键都是唯一的。
- 键的任何数据类型:与对象不同,键可以是任何数据类型,包括函数、对象或任何原始类型。
- 可迭代: 您可以迭代 map 的键、值或条目。
基本操作
创建地图
let funnymap = new map();
将元素添加到地图
funnymap.set('a', 1); // string keyfunnymap.set(2, 'two'); // number keyfunnymap.set(true, 'yes'); // boolean keyfunnymap.set({name: 'obj'}, 'object'); // object key// funny examplefunnymap.set('knock-knock', 'who’s there?');
从地图获取值
console.log(funnymap.get('a')); // 1console.log(funnymap.get(2)); // twoconsole.log(funnymap.get(true)); // yes// funny exampleconsole.log(funnymap.get('knock-knock')); // who’s there?
检查密钥
console.log(funnymap.has('a')); // trueconsole.log(funnymap.has(42)); // false// funny exampleconsole.log(funnymap.has('chicken')); // false (it crossed the road)
删除元素
funnymap.delete('a');console.log(funnymap.has('a')); // false// funny examplefunnymap.delete('knock-knock');console.log(funnymap.get('knock-knock')); // undefined (no one answered)
获取地图的大小
console.log(funnymap.size); // 3 after deletion// funny exampleconsole.log(`the map has ${funnymap.size} jokes left.`);
清除地图
funnymap.clear();console.log(funnymap.size); // 0// funny exampleconsole.log(`all jokes are cleared from the map.`);
迭代地图
用于...的
funnymap.set('banana', 'yellow');funnymap.set('apple', 'red');funnymap.set('grape', 'purple');// iterating over keysfor (let key of funnymap.keys()) { console.log(`key: ${key}`);}// iterating over valuesfor (let value of funnymap.values()) { console.log(`value: ${value}`);}// iterating over entriesfor (let [key, value] of funnymap.entries()) { console.log(`key: ${key}, value: ${value}`);}// funny examplefunnymap.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 examplefunnymap.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 wordslet 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 exampleconsole.log('Word counts in our joke:');wordCount.forEach((count, word) => { console.log(`"${word}": ${count} times`);});
概括
javascript 中的 map 是一种通用的数据结构,可以保存任何数据类型的键值对,提供简单的迭代方法,并维护元素的顺序。它对于需要比常规对象更灵活的密钥管理的场景非常有用,例如计算笑话中的单词数或存储对各种谜语的响应。