如何在 Dart 中獲取 Map<K, V> 中每個條目的索引?
具體來說,如果在物件上運行 map函式,是否可以列印出每個條目的索引,如下例所示?
例如,我如何列印出: MapEntry(Spring: 1) is index 0 MapEntry(Chair: 9) is index 1 MapEntry(Autumn: 3) is index 2 等等。
Map<String, int> exampleMap = {"Spring" : 1, "Chair" : 9, "Autumn" : 3};
void main() {
exampleMap.entries.map((e) { return print(e);}).toList(); ///print each index here
}
-注意:我可以使用 List 物件獲取索引(例如通過使用 exampleList.indexOf(e)),但不確定在使用 Map 物件時如何執行此操作。
uj5u.com熱心網友回復:
您可以使用forEachand 一個變數來跟蹤當前索引:
Map<String, int> exampleMap = {"Spring": 1, "Chair": 9, "Autumn": 3};
void main() {
int i = 0;
exampleMap.forEach((key, value) {
print(i.toString());
print(key);
print(value);
i ;
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/453480.html
下一篇:使用Django,將Python字典發送到HTML頁面并將其轉換為Javascript腳本中的Javascript陣列
