javascript 中的 map 是键值对的集合,其中键可以是任何类型。它保留插入的顺序,这意味着项目按照添加的顺序进行迭代。
地图的主要特征;
let funnymap = new map();
funnymap.set('a', 1); // string key funnymap.set(null, '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}`); }
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 中的 map 是一种通用的数据结构,可以保存任何数据类型的键值对,提供简单的迭代方法,并维护元素的顺序。它对于需要比常规对象更灵活的密钥管理的场景非常有用,例如计算笑话中的单词数或存储对各种谜语的响应。