Map 保存鍵值對,其中鍵可以是任何數(shù)據(jù)類型。
Map 會記住鍵的原始插入順序。
Map 提供表示映射大小的屬性。
Map 方法
方法 | 描述 |
---|---|
new Map() | 創(chuàng)建新的 Map 對象。 |
set() | 為 Map 中的鍵設(shè)置值。 |
get() | 獲取 Map 對象中鍵的值。 |
clear() | 從 Map 中移除所有元素。 |
delete() | 刪除由某個鍵指定的 Map 元素。 |
has() | 如果鍵存在于 Map 中,則返回 true。 |
forEach() | 為 Map 中的每個鍵/值對調(diào)用回調(diào)函數(shù)。 |
entries() | 返回迭代器對象,其中包含 Map 中的 [key, value] 鍵值對。 |
keys() | 返回迭代器對象,其中包含 Map 中的鍵。 |
values() | 返回迭代器對象,其中包含 Map 中的值。 |
屬性 | 描述 |
---|---|
size | 返回 Map 元素的數(shù)量。 |
如何創(chuàng)建 Map
您可以通過以下方式創(chuàng)建 JavaScript 映射:
- 將數(shù)組傳遞給 new Map()
- 創(chuàng)建映射并使用 Map.set()
new Map()
您可以通過將數(shù)組傳遞給 new Map() 構(gòu)造函數(shù)來創(chuàng)建 Map:
// 創(chuàng)建一個 Map
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);
您也可以使用 set() 方法將元素添加到 Map 中:
// 創(chuàng)建一個 Map
const fruits = new Map();
// 設(shè)置 Map 的值
fruits.set("apples", 500);
fruits.set("bananas", 300);
fruits.set("oranges", 200);
set() 方法還可用于更改現(xiàn)有的 Map 值:
fruits.set("apples", 500);
Map.get()
get() 方法獲取 Map 中鍵的值:
fruits.get("apples"); // 返回 500
Map.size
size 屬性返回 Map 中元素的數(shù)量:
fruits.size;
Map.clear()
clear() 方法從 Map 中刪除所有元素:
fruits.clear();
如果 Map 中存在鍵,則 has() 方法返回 true:
fruits.has("apples");
請試試這個:
fruits.delete("apples");
fruits.has("apples");
typeof 返回 object:
// 返回 object:
typeof fruits;
instanceof Map 返回 true:
// 返回 true:
fruits instanceof Map;
JavaScript Object 對比 Map
Object(對象) | Map(映射) |
---|---|
不可直接迭代 | 可直接迭代 |
無 size 屬性 | 有 size 屬性 |
鍵必須是字符串(或符號) | 鍵可以是任何數(shù)據(jù)類型 |
鍵不排序 | 鍵按插入排序 |
有默認(rèn)鍵 | 沒有默認(rèn)鍵 |
?
Map.forEach()
forEach() 方法為 Map 中的每個鍵/值對調(diào)用回調(diào):
// 列出所有條目
let text = "";
fruits.forEach (function(value, key) {
text += key + ' = ' + value;
})
Map.entries()
entries() 方法返回一個帶有 Map 中 [key,values] 的迭代器對象:
// 列出所有條目
let text = "";
for (const x of fruits.entries()) {
text += x;
}
Map.keys()
keys() 方法返回一個迭代器對象,其中包含 Map 中的鍵:
// 列出所有鍵
let text = "";
for (const x of fruits.keys()) {
text += x;
}
values() 方法返回一個迭代器對象,其中包含 Map 中的值:
// 列出所有值
let text = "";
for (const x of fruits.values()) {
text += x;
}
您可以使用 values() 方法對 Map 中的值求和:
// 對所有值求和
let total = 0;
for (const x of fruits.values()) {
total += x;
}
將對象用作鍵
能夠?qū)ο笥米麈I是 Map 的一項重要特性。文章來源:http://www.zghlxwxcb.cn/news/detail-823943.html
// 創(chuàng)建對象
const apples = {name: 'Apples'};
const bananas = {name: 'Bananas'};
const oranges = {name: 'Oranges'};
// 創(chuàng)建 Map
const fruits = new Map();
// Add new Elements to the Map
fruits.set(apples, 500);
fruits.set(bananas, 300);
fruits.set(oranges, 200);
請記住:鍵是對象(apples),而不是字符串(“apples”):文章來源地址http://www.zghlxwxcb.cn/news/detail-823943.html
fruits.get("apples"); // 返回 undefined
到了這里,關(guān)于高級編程JavaScript中的Map鍵值對你知道嗎?一篇文章看懂的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!