1. 程式人生 > 其它 >Dart 資料型別 - Map

Dart 資料型別 - Map

Map 是一個無序的鍵值對(key-value)對映,通常被稱為雜湊或字典。
宣告方式 (1)、字面量        var map = { key1: value1, key2: value2 }; (2)、建構函式        var map = new Map();        map['key'] = value;
  // 宣告 - 字面量
  var person = {'name': 'bob', 'age': 20};
  print(person); // {name: bob, age: 20}

  // 宣告 - 建構函式
  var p = new Map();
  p['name'] = 'kobe';
  p['age'] = 42;
  print(p); 
// {name: kobe, age: 42}

 

屬性 (1)、map[key]:訪問屬性 (2)、length → int :返回鍵值對的數量 (3)、keys → Iterable<K> :返回一個只包含鍵名的可迭代物件 (4)、values → Iterable<V> :返回一個只包含鍵值的可迭代物件 (5)、isEmpty → bool :檢測map是否為空
  // 訪問屬性
  print(person['name']); // bob
  // 返回鍵值對的數量
  print(person.length); // 2
  // 返回一個只包含鍵名的可迭代物件
  print(person.keys); //
(name, age) // 返回一個只包含鍵值的可迭代物件 print(person.values); // (bob, 20) // 檢測map是否為空 bool isEmpty = person.isEmpty; print(isEmpty); // false

 

方法 (1)、addAll(Map<K, V> other) → void :新增一個map (2)、containsKey(Object? key) → bool :判斷map中的key是否存在 (3)、putIfAbsent(K key, V ifAbsent()) → V :如果key存在,就不賦值;如果key不存在,就賦值 (4)、remove(Object? key) → V? :刪除指定的鍵值對 (5)、removeWhere(bool test(K key, V value)) → void :根據條件進行刪除 (6)、clear() → void :清空map
  //
addAll() person.addAll({'city': 'beijing', 'country': 'china'}); print(person); // {name: bob, age: 20, city: beijing, country: china} // containsKey() bool hasCity = person.containsKey('city'); print(hasCity); // true // putIfAbsent() person.putIfAbsent('city', () => 'hangzhou'); print(person); // {name: bob, age: 20, city: beijing, country: china} person.putIfAbsent('gender', () => 'male'); print( person); // {name: bob, age: 20, city: beijing, country: china, gender: male} // remove() final removedValue = person.remove('country'); print(removedValue); // china print(person); // {name: bob, age: 20, city: beijing, gender: male} // removeWhere() person.removeWhere((key, value) => key == 'gender'); print(person); // {name: bob, age: 20, city: beijing} // clear() person.clear(); print(person); // {}

 

遍歷 (1)、forEach(void action(K key, V value)) → void (2)、map<K2, V2>(MapEntry<K2, V2> convert(K key, V value)) → Map<K2, V2>
  // forEach()
  final score = {'chinese': 145, 'math': 138, 'english': 142};
  score.forEach((key, value) {
    print('$key, $value');
  });

  // map() 給每一科成績都加5分
  final newScore = score.map((key, value) => new MapEntry(key, value + 5));
  print(newScore); // {chinese: 150, math: 143, english: 147}