Map 字典

Map

CBrother字典是类似 "key" => "value" 这样的键值对集合,key可以是任意对象。字典的元素没有特定的顺序,如果顺序很重要的话就要使用数组了。

函数描述参数返回值用法
add(key,value) 添加元素,重复key会失败 key:键值,value:元素 添加结果。true:成功,false:失败 myMap.add("tony","age 18")
get(key) 获取键值对应的元素 key:键值 key对应的元素 myMap.get("tony")
set(key,value) 修改键值对应的元素 key:键值,value:新元素 修改结果。true:成功,false:失败 myMap.set("tony","age 20")
remove(key) 移除键值对应的元素 key:键值 被移除的元素 var delobj = myMap.remove("tony")
size() 获取字典元素个数 字典元素个数 var nowsize = myMap.size()
clear() 清空字典 myMap.clear()

例子:

  1. function main(parm)
  2. {
  3. var myMap = new Map();
  4. myMap.add("tony","age 18");
  5. myMap.add("jim","age 19");
  6. myMap.add("lily","age 17");
  7. var len = myMap.size();
  8. print "myMap size:" + len;
  9. print "tony:" + myMap.get("tony");
  10. print "jim:" + myMap.get("jim");
  11. print "lily:" + myMap.get("lily");
  12. myMap.remove("jim");
  13. myMap.set("tony","age 17");
  14. len = myMap.size();
  15. print "after remove. myMap size:" + len;
  16. print "tony:" + myMap.get("tony");
  17. print "lily:" + myMap.get("lily");
  18. myMap.clear();
  19. len = myMap.size();
  20. print "after clear. myMap size:" + len;
  21. }

结果:

  1. myMap size:3
  2. tony:age 18
  3. jim:age 19
  4. lily:age 17
  5. after remove. myMap size:2
  6. tony:age 17
  7. lily:age 17
  8. after clear. myMap size:0

Map也可以用{}来初始化:

  1. function main(parm)
  2. {
  3. var myMap = {"tony":"age 18","jim":"age 19"};
  4. myMap["lily"] = "age 17";
  5. var len = myMap.size();
  6. print "myMap size:" + len;
  7. print "tony:" + myMap.get("tony");
  8. print "jim:" + myMap.get("jim");
  9. print "lily:" + myMap.get("lily");
  10. }

结果:

  1. myMap size:3
  2. tony:age 18
  3. jim:age 19
  4. lily:age 17

foreach支持

  1. function main(parm)
  2. {
  3. var myMap = {"tony":"age 18","jim":"age 19","lily":"age 17"};
  4. foreach(k,v : map)
  5. {
  6. print k + ":" + v;
  7. }
  8. print "========================";
  9. foreach(k,v : map)
  10. {
  11. if(key == "lily")
  12. {
  13. foreach_del;
  14. continue;
  15. }
  16. print k + ":" + v;
  17. }
  18. }

结果:

  1. jim:age 19
  2. lily:age 17
  3. tony:age 18
  4. ========================
  5. jim:age 19
  6. tony:age 18