在JavaScript中,Map對象允許存儲任何類型的鍵和值,提供了鍵值對的存儲功能晒奕。在HarmonyOS中绪氛,Map的使用基本遵循JavaScript的標(biāo)準(zhǔn)唆鸡,尤其是要注意set賦值只能用get獲取,而索引賦值只能用索引獲取枣察。且它們可以同時賦值但遍歷的方式又不同争占。
【Map 對象的賦值與獲取】
- 使用set方法賦值
當(dāng)你需要創(chuàng)建一個Map對象并為其設(shè)置初始值時燃逻,可以使用new Map()構(gòu)造函數(shù),并傳入一個由鍵值對組成的數(shù)組燃乍。一旦通過set方法設(shè)置了值唆樊,那么必須使用get方法來檢索這些值。
let p: Map<string, string> = new Map([["mobile", "13444444444"]]);
p.set('aaa', '111');
console.info(`p.get('mobile'):` + p.get('mobile'));
console.info(`p.get('aaa'):` + p.get('aaa'));
- 使用Object.entries轉(zhuǎn)換為Map
如果你有一個對象刻蟹,并希望將其轉(zhuǎn)換為Map對象逗旁,可以利用Object.entries方法來實現(xiàn)這一點。此方法將對象的所有可枚舉屬性轉(zhuǎn)換成鍵值對數(shù)組舆瘪,然后可以用這些數(shù)組來初始化Map片效。
let strParam = '{"main":"aasadada","ks":"sadadas","sc":11111,"update":"asdasdasda"}';
let obj: object = JSON.parse(strParam);
let p2: Map<string, string | number> = new Map(Object.entries(obj));
console.info(`p2.get('main'): ${p2.get('main')}`);
- 使用索引賦值
當(dāng)處理從接口API返回的數(shù)據(jù)時,可能需要將JSON字符串直接解析為Map英古。需要注意的是淀衣,雖然可以這樣做,但是當(dāng)嘗試通過索引訪問時召调,必須確保數(shù)據(jù)類型正確膨桥。
let jsonStr2 = `{"mobile2":"哈哈哈"}`;
let p3 = JSON.parse(jsonStr2) as Map<string, Object>;
console.info(`p3['mobile2']:${p3['mobile2']}`);
【Map 的遍歷】
Map對象支持多種遍歷方式,這取決于你是如何賦值的唠叛。
- 使用forEach遍歷
對于通過set方法賦值的Map只嚣,推薦使用forEach來進行遍歷。
p.forEach((value, key) => {
console.info(`Key (set): ${key}, Value (set): ${value}`);
});
- 使用索引遍歷
如果Map是通過索引賦值的艺沼,則應(yīng)使用Object.keys結(jié)合forEach來遍歷鍵值對册舞。
Object.keys(targetMap).forEach((key) => {
console.info(`Key (index): ${key}, Value (index): ${targetMap[key]}`);
});
【完整示例】
@Entry
@Component
struct Index {
build() {
Column() {
Button('測試')
.onClick(() => {
let p1: Map<string, string> = new Map([["mobile", "13444444444"]]);
p1.set('aaa', '111');
console.info(`p1.get('mobile'):` + p1.get('mobile'));
console.info(`p1.get('aaa'):` + p1.get('aaa'));
let strParam = '{"main":"aasadada","ks":"sadadas","sc":11111,"update":"asdasdasda"}';
let obj: object = JSON.parse(strParam);
let p2: Map<string, string | number> = new Map(Object.entries(obj));
console.info(`p2.get('main'): ${p2.get('main')}`);
let jsonStr2 = `{"mobile2":"哈哈哈"}`
let p3 = JSON.parse(jsonStr2) as Map<string, Object>
console.info(`p3['mobile2']:${p3['mobile2']}`)
console.info(`遍歷p1 forEach`)
p1.forEach((value, key) => {
console.info(`Key (set): ${key}, Value (set): ${value}`);
});
console.info(`遍歷p2 forEach`)
p2.forEach((value, key) => {
console.info(`Key (set): ${key}, Value (set): ${value}`);
});
console.info(`遍歷p3 forEach`)
try {
p3.forEach((value, key) => {
console.info(`Key (set): ${key}, Value (set): ${value}`);
});
} catch (e) {
console.error(`e:${JSON.stringify(e)}`)
}
console.info(`遍歷p1 Object.keys`)
Object.keys(p1).forEach((key) => {
console.info(`Key (index): ${key}, Value (index): ${p1[key]}`);
});
console.info(`遍歷p2 Object.keys`)
Object.keys(p2).forEach((key) => {
console.info(`Key (index): ${key}, Value (index): ${p2[key]}`);
});
console.info(`遍歷p3 Object.keys`)
Object.keys(p3).forEach((key) => {
console.info(`Key (index): ${key}, Value (index): ${p3[key]}`);
});
})
}
.height('100%')
.width('100%')
}
}
打印
p1.get('mobile'):13444444444
p1.get('aaa'):111
p2.get('main'): aasadada
p3['mobile2']:哈哈哈
遍歷p1 forEach
Key (set): mobile, Value (set): 13444444444
Key (set): aaa, Value (set): 111
遍歷p2 forEach
Key (set): main, Value (set): aasadada
Key (set): ks, Value (set): sadadas
Key (set): sc, Value (set): 11111
Key (set): update, Value (set): asdasdasda
遍歷p3 forEach
e:{}
遍歷p1 Object.keys
遍歷p2 Object.keys
遍歷p3 Object.keys
Key (index): mobile2, Value (index): 哈哈哈
注意事項
? 類型一致性:確保在使用Map時,鍵和值的類型保持一致障般。
? 遍歷方式:根據(jù)賦值方式選擇正確的遍歷方法调鲸。
? 錯誤處理:在嘗試遍歷非Map類型時,應(yīng)適當(dāng)處理可能出現(xiàn)的異常挽荡。