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() |
例子:
function main(parm)
{
var myMap = new Map();
myMap.add("tony","age 18");
myMap.add("jim","age 19");
myMap.add("lily","age 17");
var len = myMap.size();
print "myMap size:" + len;
print "tony:" + myMap.get("tony");
print "jim:" + myMap.get("jim");
print "lily:" + myMap.get("lily");
myMap.remove("jim");
myMap.set("tony","age 17");
len = myMap.size();
print "after remove. myMap size:" + len;
print "tony:" + myMap.get("tony");
print "lily:" + myMap.get("lily");
myMap.clear();
len = myMap.size();
print "after clear. myMap size:" + len;
}
结果:
myMap size:3
tony:age 18
jim:age 19
lily:age 17
after remove. myMap size:2
tony:age 17
lily:age 17
after clear. myMap size:0
Map也可以用{}来初始化:
function main(parm)
{
var myMap = {"tony":"age 18","jim":"age 19"};
myMap["lily"] = "age 17";
var len = myMap.size();
print "myMap size:" + len;
print "tony:" + myMap.get("tony");
print "jim:" + myMap.get("jim");
print "lily:" + myMap.get("lily");
}
结果:
myMap size:3
tony:age 18
jim:age 19
lily:age 17
foreach支持
function main(parm)
{
var myMap = {"tony":"age 18","jim":"age 19","lily":"age 17"};
foreach(k,v : map)
{
print k + ":" + v;
}
print "========================";
foreach(k,v : map)
{
if(key == "lily")
{
foreach_del;
continue;
}
print k + ":" + v;
}
}
结果:
jim:age 19
lily:age 17
tony:age 18
========================
jim:age 19
tony:age 18