JavaScript Map的应用
Javascript Map 是一个包含多个元素的集合,其中每个元素都存储为键值对。Map对象可以同时存储对象和原始值作为键或值。当我们遍历Map对象时,它会按照插入的顺序返回键-值对。
语法:
new Map([it]);
参数:
- it: it是任何可迭代对象,其值存储为键值对。如果未指定参数,则创建一个新的映射
为空。
返回值: 一个新的Map对象。
Map的应用:
1. 数组操作: Map也可以用于根据条件改变或转换数组元素。举个例子,你可以使用map函数将一个数字数组中的每个整数翻倍。
示例: 在这个例子中,我们使用map函数将数组的元素翻倍。
JavaScript
let array = [10, 20, 30, 40, 50, 60];
let newArray = array.map((num) => {
return num * 2;
});
console.log(newArray);
输出:
(6) [20, 40, 60, 80, 100, 120]
2. 过滤数据: 使用map()方法可以通过返回仅包含满足特定条件的元素的新数组来过滤数据。这可以通过返回不满足条件的元素undefined来实现。
示例: 这里,我们将使用map()方法从数组中过滤出奇偶数。
JavaScript
let array = [1, 2, 3, 4, 5, 6];
function solution(array) {
let result = "";
array.map((item) => {
if (item % 2 === 0) {
result += "even "
} else {
result += "odd "
}
})
return result
}
console.log(solution(array));
输出:
"odd even odd even odd even "
3. 转换数据类型 : **** map() 方法可以通过应用返回不同数据类型的函数来转换数据类型。这在使用返回数据需要转换为另一种格式的 API 时非常有用。
示例: 在这里,通过使用 map() 方法,我们可以将字符串转换为数组。
Javascript
const language = "GeeksforGeeks";
const map = Array.prototype.map;
const letters = map.call(language, (eachLetter) => {
return `${eachLetter}`;
});
console.log(letters);
输出:
["G", "e", "e", "k", "s", "f", "o", "r", "G", "e", "e", "k", "s"]
4. 缓存和记忆化: 一个映射可以用来实现对昂贵函数结果或计算数据的缓存。我们可以通过使用函数参数作为键和相关结果作为值来避免冗余计算,从而优化效率。当处理计算需求高的操作或经常访问的数据可以被存储时。
示例: 这是上述方法的一个示例。
Javascript
// Caching and Memoization using Map
// Create a Map for caching computed values
const cache = new Map();
// Example function to demonstrate
// expensive computation
function myValue(n) {
console.log(`value for {n}...`);
const result = n * Math.random();
return result;
}
// Function to get a cached value or
// compute and cache if not present
function getCachedValue(n) {
if (cache.has(n)) {
console.log(`Fetching cached value for{n}...`);
return cache.get(n);
} else {
const result = myValue(n);
cache.set(n, result);
return result;
}
}
// Compute and cache for key 2
console.log(getCachedValue(2));
// Retrieve from cache for key 2
console.log(getCachedValue(2));
// Compute and cache for key 5
console.log(getCachedValue(5));
// Retrieve from cache for key 5
console.log(getCachedValue(5));
// Retrieve from cache for key 2
// (already computed)
console.log(getCachedValue(2));
输出:
value for 2...
1.7458614577470124
Fetching cached value for 2...
1.7458614577470124
value for 5...
2.590270481082264
Fetching cached value for 5...
2.590270481082264
Fetching cached value for 2...
1.7458614577470124
5. URL 路由: 在 Web 应用程序中,可以使用 Map 将 URL 路径映射到适当的处理程序或方法。处理程序函数或相关元数据可能是与 URL 路径对应的值,这种策略使得应用程序能够有效地路由和导航用户。
示例: 这是上述方法的一个示例。
JavaScript
// Create a Map for URL routing
const routes = new Map();
// Function to handle home page
function myGfg() {
console.log("Welcome to the GeeksforGeeks");
}
// Function to handle about page
function myPortal() {
console.log("A Computer secience protal.");
}
// Function to handle contact page
function myContact() {
console.log("You've reached the contact page.");
}
// Function to handle 404 (page not found) error
function notFoundHandler() {
console.log("404 - Page not found");
}
// Configure the routes
routes.set("/", myGfg);
routes.set("/about", myPortal);
routes.set("/contact", myContact);
// Function to handle incoming requests
function handleRequest(url) {
if (routes.has(url)) {
const handler = routes.get(url);
handler();
} else {
notFoundHandler();
}
}
// Simulating incoming requests
handleRequest("/"); // Home page
handleRequest("/about"); // About page
handleRequest("/contact"); // Contact page
handleRequest("/products"); // Page not found
输出结果:
Welcome to the GeeksforGeeks
A Computer secience protal.
You've reached the contact page.
404 - Page not found
以下是JavaScript中地图的一些方法
- JavaScript Map clear() 方法 : 从地图中删除所有元素并使其为空。
- JavaScript Map delete() 方法 : 从地图中删除指定的元素。
- JavaScript Map entries() 方法: 返回一个包含地图每个元素的[key, value]对的迭代器对象。
- JavaScript Map forEach() 方法 : 使用给定的函数对地图中的每个键值对执行给定的函数。
- JavaScript Map get() 方法: 返回地图中指定的元素。
- JavaScript Map has() 方法: 检查地图中是否存在具有指定键的元素。
- JavaScript Map keys() 方法: 从给定的地图对象返回键的迭代器对象。
- JavaScript Map set() 方法: 向地图对象添加键值对。
- JavaScript Map values() 方法 : 返回一个包含地图中每个元素的值的新的迭代器对象。
极客教程